Maison  >  Article  >  développement back-end  >  Comment annoter un graphique à barres groupées dans Matplotlib avec plusieurs valeurs pour chaque barre ?

Comment annoter un graphique à barres groupées dans Matplotlib avec plusieurs valeurs pour chaque barre ?

Mary-Kate Olsen
Mary-Kate Olsenoriginal
2024-10-27 10:24:30638parcourir

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

Annotations multiples pour un graphique à barres groupées

Problème :
Lors de la tentative de création d'un graphique à barres groupé à l'aide de Matplotlib, le résultat semble incorrect .

Exemple de code :

<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>

Sortie attendue :

Chaque barre doit être annotée avec sa valeur respective.

Résolution :

Méthode 1 : Utilisation de 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>

Méthode 2 : Utilisation d'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>

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn