2016-07-21 2 views
3

Если я повторить сюжет с таким же цветом и именем метки, метка будет появляться несколько раз:Matplotlib: сочетать легенду с таким же цветом и названием

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 

Но это чувствует себя очень некрасиво, есть ли хороший Сотион из Александрии? Или я просто делаю сюжет неправильно?

ответ

2

Вы должны показать только метку для одного из трех наборов данных. Это можно сделать, добавив оператор if/else в label = ... в 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() 

Это дает следующий график:

enter image description here

EDIT:

Если у вас есть разные цвета, то вы можете использовать следующий, чтобы показать легенду только один раз для каждого цвета:

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

+0

Да, это работает. Но было бы хорошо, если бы мы могли сочетать легенду с тем же именем и тем же цветом. – cqcn1991

+0

Я отредактировал свой ответ. Посмотрите, поможет ли это вам? – DavidG