Skip to main content
 首页 » 编程设计

python之在 Python Matplotlib 中更改 3D 曲面图中的网格线粗细

2025年02月15日12Renyi-Fan

我正在尝试更改构成曲面图背景中网格的线条的粗细和透明度,如下所示 example from Matplotlib's website :

这是源代码:

from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 
from matplotlib import cm 
from matplotlib.ticker import LinearLocator, FormatStrFormatter 
import numpy as np 
 
fig = plt.figure() 
ax = fig.gca(projection='3d') 
 
# Make data. 
X = np.arange(-5, 5, 0.25) 
Y = np.arange(-5, 5, 0.25) 
X, Y = np.meshgrid(X, Y) 
R = np.sqrt(X**2 + Y**2) 
Z = np.sin(R) 
 
# Plot the surface. 
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, 
                   linewidth=0, antialiased=False) 
 
# Customize the z axis. 
ax.set_zlim(-1.01, 1.01) 
ax.zaxis.set_major_locator(LinearLocator(10)) 
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) 
 
# Add a color bar which maps values to colors. 
fig.colorbar(surf, shrink=0.5, aspect=5) 
 
plt.show() 

我试过调用 ax.grid(linewidth=x) 但这似乎没有什么不同。有没有其他方法可以改变厚度?

请您参考如下方法:

在 mplot3d 中设置网格参数的一种方法是更新相应轴的 _axinfo 字典。

要设置网格在 y 方向的线宽,使用例如

ax.yaxis._axinfo["grid"]['linewidth'] = 3. 

这是一个通用的例子:

from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 
 
fig = plt.figure() 
ax = fig.gca(projection='3d') 
ax.set_xlabel("x"); ax.set_ylabel("y"); ax.set_zlabel("z") 
print ax.xaxis._axinfo 
 
ax.xaxis._axinfo["grid"].update({"linewidth":1, "color" : "green"}) 
 
ax.yaxis._axinfo["grid"]['linewidth'] = 3. 
 
ax.zaxis._axinfo["grid"]['color'] = "#ee0009" 
ax.zaxis._axinfo["grid"]['linestyle'] = ":" 
 
 
plt.show()