如果我用相同的颜色和标签名称重复绘图,标签会出现多次:
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()
Run Code Online (Sandbox Code Playgroud)
是否可以将它们合二为一,将相同的标签传说合二为一?就像是
我可以通过
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
Run Code Online (Sandbox Code Playgroud)
但是这个感觉很丑,有什么好的解决方法吗?或者我只是以错误的方式制作情节?
您应该只显示三组数据之一的标签。可以通过在label = ...in 中添加 if/else 语句来完成ax.plot()。下面是一个例子:
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()
Run Code Online (Sandbox Code Playgroud)
这给出了以下图表:
编辑:
如果您有不同的颜色,那么您可以使用以下内容为每种颜色仅显示一次图例:
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()
Run Code Online (Sandbox Code Playgroud)
这给出了以下图表: