Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python matplotlib legend shows first entry of a list only

I could not get all the legends to appear in matplotlib.

My Labels array is:

lab = ['Google', 'MSFT', 'APPL', 'EXXON', 'WMRT']

I use the below code to add the legend:

ax.legend(lab,loc="best")

Am seeing only 'Google' in top right corner. How to show all labels? enter image description here

Full code:

import numpy as np
import matplotlib.pyplot as plt
from itertools import cycle, islice

menMeans = (8092, 812, 2221, 1000, 562)
N = len(menMeans)

lab = ['Google', 'MSFT', 'APPL', 'EXXON', 'WMRT']

ind = np.arange(N)  # the x locations for the groups
width = 0.35       # the width of the bars

fig, ax = plt.subplots()
my_colors = list(islice(cycle(['b', 'r', 'g', 'y', 'k']), None, N))
rects1 = ax.bar(ind, menMeans, width, color=my_colors,label=lab)

# add some
ax.set_ylabel('Count')
ax.set_title('Trending words and their counts')
ax.set_xticks(ind+width)
ax.legend(lab,loc="best")
plt.show()
like image 719
NEO Avatar asked Apr 26 '14 22:04

NEO


People also ask

How do I change the order of items in Matplotlib legend?

Change order of items in the legend The above order of elements in the legend region can be changed by the gca method that uses another sub-method called get_legend_handles_labels method. These handles and labels lists are passed as parameters to legend method with order of indexes.

How do I fix the legend position in Matplotlib?

To change the position of a legend in Matplotlib, you can use the plt. legend() function. The default location is “best” – which is where Matplotlib automatically finds a location for the legend based on where it avoids covering any data points.

How do I stop the legend overlapping in Matplotlib?

Use pie() method to plot a pie chart with slices, colors, and slices data points as a label. Make a list of labels (those are overlapped using autopct). Use legend() method to avoid overlapping of labels and autopct. To display the figure, use show() method.


1 Answers

The answer by @Ffisegydd may be more useful*, but it doesn't answer the question. Simply create separate bar charts for the legend, and you'll get the desired result:

for x,y,c,lb in zip(ind,menMeans,my_colors,lab):
    ax.bar(x, y, width, color=c,label=lb)

ax.legend()

enter image description here

* To see why this presentation may be harmful, consider what would happen if the viewer was colorblind (or this was printed in black and white).

like image 120
Hooked Avatar answered Sep 26 '22 05:09

Hooked