Home  >  Article  >  Backend Development  >  How to annotate a grouped bar chart in Matplotlib with multiple values for each bar?

How to annotate a grouped bar chart in Matplotlib with multiple values for each bar?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-27 10:24:30638browse

How to annotate a grouped bar chart in Matplotlib with multiple values for each bar?

Multiple Annotations for Grouped Bar Chart

Problem:
When attempting to create a grouped bar chart using Matplotlib, the output appears incorrect.

Code Example:

<code class="python">import matplotlib.pyplot as plt

# sample data
labels = ['Label 1', 'Label 2', 'Label 3']
data1 = [5, 10, 15]
data2 = [15, 10, 5]

# create the bar chart
plt.bar(labels, data1, 0.4, label='Data Set 1')
plt.bar(labels, data2, 0.4, label='Data Set 2', bottom=data1)

# attempt to annotate each bar
for i in range(3):
    plt.annotate(data1[i], (labels[i], data1[i]), xytext=(-5, 5), textcoords='offset points')
    plt.annotate(data2[i], (labels[i], data2[i]+data1[i]), xytext=(-5, 5), textcoords='offset points')

plt.legend()
plt.show()</code>

Expected Output:

Each bar should be annotated with its respective value.

Resolution:

Method 1: Using bar_label

<code class="python">import matplotlib.pyplot as plt

plt.bar(labels, data1, 0.4, label='Data Set 1')
plt.bar(labels, data2, 0.4, label='Data Set 2', bottom=data1)

for i in range(3):
    plt.bar_label(plt.gca().containers[i], labels=(data1[i], data2[i]), fmt='%.1f', padding=10)

plt.legend()
plt.show()</code>

Method 2: Using annotate

<code class="python">import matplotlib.pyplot as plt

plt.bar(labels, data1, 0.4, label='Data Set 1')
plt.bar(labels, data2, 0.4, label='Data Set 2', bottom=data1)

for i in range(3):
    height1 = data1[i]
    height2 = data2[i]

    # annotate for data set 1
    plt.annotate(str(height1), (labels[i], height1), xytext=(0, 5), textcoords='offset points')

    # annotate for data set 2
    plt.annotate(str(height2), (labels[i], height1 + height2), xytext=(0, 5), textcoords='offset points')

plt.legend()
plt.show()
````
</code>

The above is the detailed content of How to annotate a grouped bar chart in Matplotlib with multiple values for each bar?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn