Python matplotlib legend shows first entry of list only

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

My Labels Array:

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

I use the code below to add a legend:

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

I see only "Google" in the upper right corner. How to show all shortcuts? 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()
+4
source share
2 answers

@Ffisegydd's answer may be more helpful *, but it doesn't answer the question. Just create separate histograms for the legend, and you will 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 understand why this presentation can be harmful, think about what would happen if the viewer was colorblind (or it was printed in black and white).

+2
source

, ax.bar, ( ). , script, - xticks xticklabels, .

, matplotlib.artist, . , , . , 5 10 , - . , .

ax.set_xticks(ind+width/2) , , lab ax.set_xticklabels(lab).

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

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)

ax.set_ylabel('Count')
ax.set_title('Trending words and their counts')

plt.xticks(rotation=90)

ax.set_xticks(ind+width/2)
ax.set_xticklabels(lab)

plt.show()

Plot

+3

Source: https://habr.com/ru/post/1538229/


All Articles