如何解决Matplotlib中gca方法传入projection参数的报错问题?
解决Matplotlib 3D绘图中
fig.gca(projection='3d')的报错问题 报错原因
Matplotlib 3.4及以上版本移除了Figure.gca()方法的projection参数,旧写法fig.gca(projection='3d')不再兼容,因此抛出TypeError。
修复方案
提供两种可行的替代写法,同时修正代码中另一个潜在错误:
方案1:使用fig.add_subplot()创建3D轴
替换原代码中创建轴的行,改用add_subplot()指定3D投影:
import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np # 假设X、Y、Z已提前定义 fig = plt.figure(figsize=(10, 6)) # 替换原fig.gca(projection='3d') ax = fig.add_subplot(projection='3d') surf1 = ax.plot_surface(X, Y, Z, rstride=2, cstride=2, cmap=mpl.cm.coolwarm, linewidth=0.5, antialiased=True) surf2 = ax.plot_wireframe(X, Y, Z, rstride=2, cstride=2, label='regression') ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('f(x, y)') ax.legend() # 修正变量名:原代码中surf未定义,改为surf1 fig.colorbar(surf1, shrink=0.5, aspect=5) plt.show()
方案2:使用plt.subplots()直接创建带3D投影的轴
这种写法更简洁,一步完成画布和轴的创建:
import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np # 假设X、Y、Z已提前定义 fig, ax = plt.subplots(figsize=(10, 6), subplot_kw={'projection': '3d'}) surf1 = ax.plot_surface(X, Y, Z, rstride=2, cstride=2, cmap=mpl.cm.coolwarm, linewidth=0.5, antialiased=True) surf2 = ax.plot_wireframe(X, Y, Z, rstride=2, cstride=2, label='regression') ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('f(x, y)') ax.legend() fig.colorbar(surf1, shrink=0.5, aspect=5) plt.show()
额外说明
原代码中fig.colorbar(surf, ...)的surf变量未定义,需改为实际创建的曲面对象surf1,否则会触发NameError。
内容的提问来源于stack exchange,提问作者cryptomamy
相关产品推荐
相关产品推荐

