python - 有没有办法在 matplotlib 中标记多个 3d 表面?

标签 python matplotlib

我尝试解决具有线性约束的非线性数学优化问题。为此,我尝试在 3d 中可视化约束以查看发生了什么,以及为什么我为约束中的某些参数而不是其他参数获得了可行的解决方案。

为了实现这一点,我想使用 python 中的 ma​​tplotlib 生成 3d 表面(平面,因为我所有的约束都是线性的)。

但是,如果没有绘图内标记,则很难识别哪个表面属于哪个约束。这让我想寻找一种方法来在绘图中添加带有颜色的图例。

我认识到在方法 ax.plot()ax.scatter() 中已经有一种方法可以在 2D 中执行此操作,但我正在尝试这样做同样不适用于 ax.plot_surface(X, Y, Z, label = 'mylabel')

完整脚本如下:


from mpl_toolkits import mplot3d
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np


fig = plt.figure()
ax = plt.axes(projection='3d')

plt.rcParams['legend.fontsize'] = 10


# First constraint
g2 = np.linspace(-5,5,2)
g3 = np.linspace(-5,5,2)
G2,G3 = np.meshgrid(g2,g3)
G4_1 = -1.18301270189222 - 0.5*G2 + 0.5*G3
ax = fig.gca(projection='3d')
c1 = ax.plot_surface(G2, G3, G4_1, label = "c1")

# Second
G3, G4 = np.meshgrid(g2, g3)
G2 = G3
c2 = ax.plot_surface(G2, G3, G4, label = "c2")

# Third
G2,G3 = np.meshgrid(g2,g3)
G4 = (0.408248290463863*G2 + 0.408248290463863*G3 -0.707106781186548)/1.63299316185545
c3 = ax.plot_surface(G2, G3, G4, label = "c3")

# And forth
G4 = (1.04903810567666 - (0.288675134594813*G2 + 0.288675134594813*G3))/0.577350269189626
c4 = ax.plot_surface(G2, G3, G4, label="c4")



ax.legend() # -> error : 'AttributeError: 'Poly3DCollection' object has no attribute '_edgecolors2d''


# labeling the figure
fig.suptitle("Constraints")
#plt.xlabel('g2', fontsize=14)
#plt.ylabel('g3', fontsize=14)
ax.set_xlabel(r'$g_2$', fontsize=15, rotation=60)
ax.set_ylabel('$g_3$', fontsize=15, rotation=60)
ax.set_zlabel('$g_4$', fontsize=15, rotation=60)
plt.savefig('Constraints.jpg')
plt.show()

结果如下图。

plot

正如您可能已经看到的,无法分辨哪个表面属于哪个约束,我想要实现的是一个图例,例如 here .

我通读了this question的答案,但它在这里不起作用,因为我有多个表面。尝试后,它一直只显示一个标签,而不是四个。

所以我的问题是,有没有办法向我的 ax.plot_surface 或任何其他合适的 hack 添加图例?

最佳答案

这是对 @Gio's answer 的更新.从 matplotlib 3.3.3 开始,_facecolors3d_edgecolors3d 不存在。所以,而不是这个:

c1._facecolors2d = c1._facecolors3d
c1._edgecolors2d = c1._edgecolors3d

这会导致类似的AttributeError,试试这个:

c1._facecolors2d = c1._facecolor3d
c1._edgecolors2d = c1._edgecolor3d

由于代表率低,我不得不将其作为答案而不是评论。

关于python - 有没有办法在 matplotlib 中标记多个 3d 表面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55531760/

相关文章:

python - 类型错误 : %d format: a number is required, 不是 numpy.float64

python - 尝试在 Tkinter 中使用来自 Matplotlib 的鼠标事件的日期时间

python - 具有兄弟目录的 Python (3.4) 中的绝对或相对导入

python - 如何更改seaborn联合图中文本的位置

python - 使用 Python 示例对多项式朴素贝叶斯分类器进行分类

python - 具有可变长度序列掩码的 LSTM 变分自动编码器

Python 登录脚本;用户名和密码位于单独的文件中

python - 使用 matplotlib,是否可以一次为图形上的所有子图设置属性?

python - 将平面投影到新坐标系上

python - 如何为条形图添加组标签