If I repeat the plot with same color and label name, the label would appear multiple times:
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()
Is it possible to make them into one, combing the same lables legends into one? Something like
I can produce the above pic by
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
But this feels very ugly, is there any good sotion? Or do I simply make the plot in a wrong way?
MatPlotLib with PythonPlace the first legend at the upper-right location. Add artist, i.e., first legend on the current axis. Place the second legend on the current axis at the lower-right location. To display the figure, use show() method.
MatPlotLib with Python To place the legend, use legend() method with location of the legend and store the returned value to set the color of the text. To set the color of the text, use set_color() method with green color. To display the figure, use show() method.
You should only show the label for one of the three sets of data. The can be done by adding an if/else statement in the label = ...
in ax.plot()
. Below is an example:
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()
This gives the following graph:
EDIT:
If you have different colors then you could use the following to show the legend only once for each color:
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()
This gives the following graph:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With