Matplotlib- Bars
Bars erstellen
Mit Pyplot können Sie die bar()
Funktion zum Zeichnen von Balkendiagrammen verwenden:
Beispiel
Zeichne 4 Balken:
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A",
"B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.bar(x,y)
plt.show()
Ergebnis:
Die bar()
Funktion akzeptiert Argumente, die das Layout der Balken beschreiben.
Die Kategorien und ihre Werte, die durch das erste und zweite Argument als Arrays dargestellt werden.
Beispiel
x = ["APPLES", "BANANAS"]
y = [400, 350]
plt.bar(x, y)
Horizontale Balken
Wenn Sie möchten, dass die Balken horizontal statt vertikal angezeigt werden, verwenden Sie die barh()
Funktion:
Beispiel
Zeichne 4 horizontale Balken:
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A",
"B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.barh(x, y)
plt.show()
Ergebnis:
Balkenfarbe
Das bar()
and barh()
nimmt das Schlüsselwortargument
color
, um die Farbe der Balken festzulegen:
Beispiel
Zeichne 4 rote Balken:
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A",
"B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.bar(x, y, color = "red")
plt.show()
Ergebnis:
Farbnamen
Sie können jeden der 140 unterstützten Farbnamen verwenden .
Beispiel
Zeichne 4 "Pink"-Balken:
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A",
"B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.bar(x, y, color = "hotpink")
plt.show()
Ergebnis:
Farbe Hex
Oder Sie können hexadezimale Farbwerte verwenden :
Beispiel
Zeichne 4 Balken mit einer schönen grünen Farbe:
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A",
"B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.bar(x, y, color = "#4CAF50")
plt.show()
Ergebnis:
Balkenbreite
Das verwendet bar()
das Schlüsselwortargument
width
, um die Breite der Balken festzulegen:
Beispiel
Zeichne 4 sehr dünne Balken:
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A",
"B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.bar(x, y, width = 0.1)
plt.show()
Ergebnis:
Der Standardwert für die Breite ist 0,8
Hinweis: Verwenden Sie für horizontale Balken height
anstelle von width
.
Stangenhöhe
Das verwendet barh()
das Schlüsselwortargument
height
, um die Höhe der Balken festzulegen:
Beispiel
Zeichne 4 sehr dünne Balken:
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A",
"B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.barh(x, y, height = 0.1)
plt.show()
Ergebnis:
Der Standardwert für die Höhe ist 0,8