gpt4 book ai didi

python - Matplotlib:将具有相同颜色和名称的图例组合起来

转载 作者:太空宇宙 更新时间:2023-11-03 10:57:50 32 4
gpt4 key购买 nike

如果我用相同的颜色和标签名称重复绘图,标签将出现多次:

from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.gca(projection='3d')

x_labels = [10,20,30]
x = [1,2,3,4]
y = [3,1,5,1]

for label in x_labels:
x_3d = label*np.ones_like(x)
ax.plot(x_3d, x, y, color='black', label='GMM')

ax.legend()

enter image description here

是否可以将它们合二为一,将相同的标签图例组合成一个?有点像

enter image description here

我可以制作上面的图片

from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.gca(projection='3d')

x_labels = [10,20,30]
x = [1,2,3,4]
y = [3,1,5,1]
legend = False

for label in x_labels:
x_3d = label*np.ones_like(x)
ax.plot(x_3d, x, y, color='black', label='GMM')
if legend == False:
ax.legend()
legend = True

但是这个感觉很丑,请问有什么好的药水吗?还是我只是以错误的方式制作了情节?

最佳答案

您应该只显示三组数据之一的标签。这可以通过在 ax.plot()label = ... 中添加 if/else 语句来完成。下面是一个例子:

from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.gca(projection='3d')

x_labels = [10,20,30]
x = [1,2,3,4]
y = [3,1,5,1]

for label in x_labels:
x_3d = label*np.ones_like(x)
ax.plot(x_3d, x, y, color='black', label='GMM' if label == x_labels[0] else '')
# above only shows the label for the first plot

ax.legend()

plt.show()

这给出了下图:

enter image description here

编辑:

如果您有不同的颜色,那么您可以使用以下代码为每种颜色仅显示一次图例:

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

x_labels = [10,20,30,40,50]
x = [1,2,3,4]
y = [3,1,5,1]

colors = ['black','red','black','orange','orange']
labels = ['GMM','Other 1','GMM','Other 2','Other 2']
some_list= []

for i in range(len(x_labels)):
x_3d = x_labels[i]*np.ones_like(x)
ax.plot(x_3d, x, y, color=colors[i], label=labels[i] if colors[i] not in some_list else '')

if colors.count(colors[i])>1:
some_list.append(colors[i])

ax.legend()

plt.show()

这给出了下图:

enter image description here

关于python - Matplotlib:将具有相同颜色和名称的图例组合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38501822/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com