Home > Software engineering >  Why the plot is not showing the legend
Why the plot is not showing the legend

Time:10-02

I have problems in showing the legend in a plot. The example code below was taken from matplotlib documentation. The plot shows a single color (red) in the legend. I also do not understand what is the role of bar_labels in the code. I thank you for any comment.

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fruits = ['apple', 'blueberry', 'cherry', 'orange']
counts = [40, 100, 30, 55]
bar_labels = ['red', 'blue', '_red', 'orange']
bar_colors = ['tab:red', 'tab:blue', 'tab:red', 'tab:orange']

ax.bar(fruits, counts, label=bar_labels, color=bar_colors)

ax.set_ylabel('fruit supply')
ax.set_title('Fruit supply by kind and color')
ax.legend(title='Fruit color')
ax.legend()

plt.show()

CodePudding user response:

The bar_label consists of the labels (text next to each legend color) for each of the bars. label=ABC in your plot tells matplotlib that it should give the name ABC to the label for that color. Also, if there is an underscore (_), matplotlib will ignore that line. So, the label of red will be considered, while _red will be ignored. In your code, as you are giving each data point individually, you can make this change and it should work. Note that you should probably change the labels of red to apple/cherry, blue to blueberry, etc.

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fruits = ['apple', 'blueberry', 'cherry', 'orange']
counts = [40, 100, 30, 55]
bar_labels = ['red', 'blue', '_red', 'orange']
bar_colors = ['tab:red', 'tab:blue', 'tab:red', 'tab:orange']

for i in range(len(fruits)):
    ax.bar(fruits[i], counts[i], color=bar_colors[i], label=bar_labels[i])

ax.set_ylabel('fruit supply')
ax.set_title('Fruit supply by kind and color')
ax.legend(title='Fruit color')
ax.legend()
plt.show()

enter image description here

CodePudding user response:

You are probably referring to enter image description here

  • Related