So zeigen Sie den Wert des Balkens auf jedem Balken mit pyplot.barh() an

Lesezeit: 7 Minuten

Benutzeravatar von Franck Dernoncourt
Frank Dernoncourt

Ich habe ein Balkendiagramm erstellt, wie kann ich den Wert des Balkens auf jedem Balken anzeigen?

Aktuelle Handlung:

Geben Sie hier die Bildbeschreibung ein

Was ich versuche zu bekommen:

Geben Sie hier die Bildbeschreibung ein

Mein Code:

import os
import numpy as np
import matplotlib.pyplot as plt

x = [u'INFO', u'CUISINE', u'TYPE_OF_PLACE', u'DRINK', u'PLACE', u'MEAL_TIME', u'DISH', u'NEIGHBOURHOOD']
y = [160, 167, 137, 18, 120, 36, 155, 130]

fig, ax = plt.subplots()    
width = 0.75 # the width of the bars 
ind = np.arange(len(y))  # the x locations for the groups
ax.barh(ind, y, width, color="blue")
ax.set_yticks(ind+width/2)
ax.set_yticklabels(x, minor=False)
plt.title('title')
plt.xlabel('x')
plt.ylabel('y')      
#plt.show()
plt.savefig(os.path.join('test.png'), dpi=300, format="png", bbox_inches="tight") # use format="svg" or 'pdf' for vectorial pictures

Benutzeravatar von cphlewis
cphlewis

Update: Dafür gibt es jetzt eine eingebaute Methode! Scrollen Sie ein paar Antworten nach unten zu “Neu in Matplotlib 3.4.0”.

Wenn Sie nicht so weit upgraden können, ist nicht viel Code erforderlich. Hinzufügen:

for i, v in enumerate(y):
    ax.text(v + 3, i + .25, str(v), color="blue", fontweight="bold")

Ergebnis:

Geben Sie hier die Bildbeschreibung ein

Die y-Werte v sind sowohl die x-Position als auch die Zeichenfolgenwerte für ax.textund praktischerweise hat das Balkendiagramm eine Metrik von 1 für jeden Balken, also die Aufzählung i ist die y-Position.

  • Ersetzen Sie möglicherweise va = ‘center’ anstelle von “i + .25” für die horizontale Ausrichtung

    – mathaus

    26. September 2017 um 16:40 Uhr

  • plt.text(v, i, " "+str(v), color='blue', va='center', fontweight='bold')

    – João Cartucho

    18. April 2018 um 11:41 Uhr


  • Wie kann ich die Textausgabe in einem Jupyter-Notebook unterdrücken? “;” am Ende geht nicht.

    – Ralf Hundewadt

    17. Juli 2019 um 14:58 Uhr

  • Wenn ich NEIGHBORHOOD oben auf der Bar und dasselbe für alle Baove-Bars drucken möchte, anstatt auf der linken Seite, was getan werden muss. habe an vielen Stellen versucht und gesucht, aber bis jetzt keine Ahnung.

    – Rishi Bansal

    19. Juli 2019 um 10:55 Uhr


  • @RalfHundewadt habe gerade a gesetzt plt.show() Klausel am Ende. Zum Beispiel: df.plot(); plt.show()

    – Jairo Alves

    14. Oktober 2019 um 18:51 Uhr

Benutzeravatar von tdy
tdy

Neu in matplotlib 3.4.0

Es gibt jetzt eine eingebaute Axes.bar_label Hilfsmethode zum automatischen Beschriften von Balken:

fig, ax = plt.subplots()
bars = ax.barh(indexes, values)

ax.bar_label(bars)

Beachten Sie, dass es für gruppierte/gestapelte Balkendiagramme mehrere Balkencontainer gibt, auf die alle über zugegriffen werden kann ax.containers:

for bars in ax.containers:
    ax.bar_label(bars)

Mehr Details:

  • So fügen Sie Tausendertrennzeichen (Kommas) zu Etiketten hinzu
  • So wenden Sie F-Strings auf Etiketten an
  • So fügen Sie Etiketten Abstand hinzu

GDPZM

  • Endlich ist es da! Ein guter Grund für ein Upgrade auf matplotlib 3.4.0!

    – ilija139

    19. Dezember 2022 um 9:53 Uhr

Benutzeravatar von Franck Dernoncourt
Frank Dernoncourt

Ich habe bemerkt API-Beispielcode enthält ein Beispiel für ein Balkendiagramm mit dem Wert des Balkens, der auf jedem Balken angezeigt wird:

"""
========
Barchart
========

A bar plot with errorbars and height labels on individual bars
"""
import numpy as np
import matplotlib.pyplot as plt

N = 5
men_means = (20, 35, 30, 35, 27)
men_std = (2, 3, 4, 1, 2)

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

fig, ax = plt.subplots()
rects1 = ax.bar(ind, men_means, width, color="r", yerr=men_std)

women_means = (25, 32, 34, 20, 25)
women_std = (3, 5, 2, 3, 3)
rects2 = ax.bar(ind + width, women_means, width, color="y", yerr=women_std)

# add some text for labels, title and axes ticks
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind + width / 2)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))

ax.legend((rects1[0], rects2[0]), ('Men', 'Women'))


def autolabel(rects):
    """
    Attach a text label above each bar displaying its height
    """
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
                '%d' % int(height),
                ha="center", va="bottom")

autolabel(rects1)
autolabel(rects2)

plt.show()

Ausgang:

Geben Sie hier die Bildbeschreibung ein

FYI Was ist die Einheit der Höhenvariablen in “barh” von matplotlib? (derzeit gibt es keine einfache Möglichkeit, eine feste Höhe für jeden Balken festzulegen)

Benutzeravatar von Anirvan Sen
Anirvan Sen

Verwenden plt.text() um Text in die Handlung einzufügen.

Beispiel:

import matplotlib.pyplot as plt
N = 5
menMeans = (20, 35, 30, 35, 27)
ind = np.arange(N)

#Creating a figure with some fig size
fig, ax = plt.subplots(figsize = (10,5))
ax.bar(ind,menMeans,width=0.4)
#Now the trick is here.
#plt.text() , you need to give (x,y) location , where you want to put the numbers,
#So here index will give you x pos and data+1 will provide a little gap in y axis.
for index,data in enumerate(menMeans):
    plt.text(x=index , y =data+1 , s=f"{data}" , fontdict=dict(fontsize=20))
plt.tight_layout()
plt.show()

Dies zeigt die Abbildung als:

Balkendiagramm mit Werten oben

Für alle, die es haben wollen Etikett an der Basis ihrer Bars nur dividiere v durch den Wert des Labels so was:

for i, v in enumerate(labels):
    axes.text(i-.25, 
              v/labels[i]+100, 
              labels[i], 
              fontsize=18, 
              color=label_color_list[i])

(Anmerkung: Ich habe 100 hinzugefügt, damit es nicht ganz unten war)

Um ein Ergebnis wie dieses zu erhalten:
Geben Sie hier die Bildbeschreibung ein

Ich weiß, es ist ein alter Thread, aber ich bin mehrmals über Google hier gelandet und finde, dass noch keine Antwort wirklich befriedigend ist. Versuchen Sie es mit einer der folgenden Funktionen:

BEARBEITEN: Da ich in diesem alten Thread einige Likes bekomme, möchte ich auch eine aktualisierte Lösung teilen (im Grunde füge ich meine beiden vorherigen Funktionen zusammen und entscheide automatisch, ob es sich um ein Balken- oder Hbar-Diagramm handelt):

def label_bars(ax, bars, text_format, **kwargs):
    """
    Attaches a label on every bar of a regular or horizontal bar chart
    """
    ys = [bar.get_y() for bar in bars]
    y_is_constant = all(y == ys[0] for y in ys)  # -> regular bar chart, since all all bars start on the same y level (0)

    if y_is_constant:
        _label_bar(ax, bars, text_format, **kwargs)
    else:
        _label_barh(ax, bars, text_format, **kwargs)


def _label_bar(ax, bars, text_format, **kwargs):
    """
    Attach a text label to each bar displaying its y value
    """
    max_y_value = ax.get_ylim()[1]
    inside_distance = max_y_value * 0.05
    outside_distance = max_y_value * 0.01

    for bar in bars:
        text = text_format.format(bar.get_height())
        text_x = bar.get_x() + bar.get_width() / 2

        is_inside = bar.get_height() >= max_y_value * 0.15
        if is_inside:
            color = "white"
            text_y = bar.get_height() - inside_distance
        else:
            color = "black"
            text_y = bar.get_height() + outside_distance

        ax.text(text_x, text_y, text, ha="center", va="bottom", color=color, **kwargs)


def _label_barh(ax, bars, text_format, **kwargs):
    """
    Attach a text label to each bar displaying its y value
    Note: label always outside. otherwise it's too hard to control as numbers can be very long
    """
    max_x_value = ax.get_xlim()[1]
    distance = max_x_value * 0.0025

    for bar in bars:
        text = text_format.format(bar.get_width())

        text_x = bar.get_width() + distance
        text_y = bar.get_y() + bar.get_height() / 2

        ax.text(text_x, text_y, text, va="center", **kwargs)

Jetzt können Sie sie für normale Balkendiagramme verwenden:

fig, ax = plt.subplots((5, 5))
bars = ax.bar(x_pos, values, width=0.5, align="center")
value_format = "{:.1%}"  # displaying values as percentage with one fractional digit
label_bars(ax, bars, value_format)

oder für horizontale Balkendiagramme:

fig, ax = plt.subplots((5, 5))
horizontal_bars = ax.barh(y_pos, values, width=0.5, align="center")
value_format = "{:.1%}"  # displaying values as percentage with one fractional digit
label_bars(ax, horizontal_bars, value_format)

Benutzeravatar von tozCSS
tozCSS

Für Pandamenschen:

ax = s.plot(kind='barh') # s is a Series (float) in [0,1]
[ax.text(v, i, '{:.2f}%'.format(100*v)) for i, v in enumerate(s)];

Das ist es. Alternativ für diejenigen, die es vorziehen apply Überschleifen mit enumerate:

it = iter(range(len(s)))
s.apply(lambda x: ax.text(x, next(it),'{:.2f}%'.format(100*x)));

Ebenfalls, ax.patches geben Ihnen die Bars, die Sie mit bekommen würden ax.bar(...). Falls Sie die Funktionen von @SaturnFromTitan oder Techniken anderer anwenden möchten.

1439820cookie-checkSo zeigen Sie den Wert des Balkens auf jedem Balken mit pyplot.barh() an

This website is using cookies to improve the user-friendliness. You agree by using the website further.

Privacy policy