olenscki
olenscki

Reputation: 507

Manage the display of labels in legend of plot

I'm trying to plot several series in one plot. From those almost 10 series, there are 2 more important ones. I'd like to make the labels in legends display in several lines under the plot (using the ncols parameter of the legend), but I'd like that the first line had only these 2 more important labels. Is it possible?

Upvotes: 0

Views: 593

Answers (1)

pakpe
pakpe

Reputation: 5479

You can simply arrange the order of ax.plot statements to get the important legends on the first row of the legends. In the following example, the Cubic and Logarithmic legend are the ones we want to appear on the first row.

import math
x_data = list(range(1,10))
y1 = [3*x for x in x_data]
y2 = [x**2 for x in x_data]
y3 = [x**3 for x in x_data]
y4 = [math.log10(x) for x in x_data]
y5 = [x*math.log10(x) for x in x_data]

fig, ax = plt.subplots()
ax.plot(x_data,y3, label= 'Cubic')#important 1
ax.plot(x_data,y1, label= 'Linear')
ax.plot(x_data,y2, label= 'Quadratic')
ax.plot(x_data,y4, label= 'Logarithmic')#important 2
ax.plot(x_data,y5, label = 'x log x')

fig.legend(loc = 'upper center',
           bbox_to_anchor = (0.5,0.8),
           ncol = 2)
plt.show()

enter image description here

UPDATE: To have 2 legend items on the first line and the rest on the second line, you need to have two separate legends. The best way to achieve this is to have twin y-axes and plot the important data on one axis and the rest on the other axis. Then you have to make sure you set the y-limits to be equal to each other and specify a color for each data set. This allows you to have ncol = 2 for the first axis legend and to some other number for the other axis legend. Finally, you can take advantage of the many arguments in legend() to make the two legends look like one. Here is how:

import math
x_data = list(range(1,10))
y1 = [3*x for x in x_data]
y2 = [x**2 for x in x_data]
y3 = [x**3 for x in x_data]
y4 = [math.log10(x) for x in x_data]
y5 = [x*math.log10(x) for x in x_data]

fig = plt.figure(figsize=(12,5))
fig.suptitle("Title")
ax1 = fig.add_subplot()
ax2 = ax1.twinx()

ax1.plot(x_data,y3, label= 'Cubic', color = 'blue')#important 1
ax1.plot(x_data,y4, label= 'Logarithmic', color = 'orange')#important 2

ax2.plot(x_data,y1, label= 'Linear', color = 'red')
ax2.plot(x_data,y2, label= 'Quadratic', color = 'green')
ax2.plot(x_data,y5, label = 'x log x', color = 'purple')

ax2.set_ylim(ax1.get_ylim()) #set the ylimits to be equal for both y axes

ax1.legend(loc = 'upper center',
           bbox_to_anchor = (0.5,0.91),
           edgecolor = 'none',
           facecolor = 'grey',
           framealpha = 0.3,
           ncol = 2)
ax2.legend(loc = 'upper center',
           bbox_to_anchor = (0.5,0.85),
           edgecolor = 'none',
           facecolor = 'grey',
           framealpha = 0.3,
           ncol = 3)

plt.show()

enter image description here

Upvotes: 1

Related Questions