Zur Erinnerung, ich hatte keinen guten Artikel.
# version
matplotlib == 3.2.2
import numpy as np
import matplotlib.pyplot as plt
#Vertikale Leiste
def barplot(ax, labels, datas):
x = np.arange(len(labels)) # the label locations
width = 0.35 # the width of the bars
rects1 = ax.bar(x - width/2, datas[0]["val"], width, label=datas[0]["label"])
rects2 = ax.bar(x + width/2, datas[1]["val"], width, label=datas[1]["label"])
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_xticks(x)
ax.set_xticklabels(labels)
#Horizontale Linie
def barhplot(ax, labels, datas):
x = np.arange(len(labels)) # the label locations
width = 0.35 # the width of the bars
rects1 = ax.barh(x - width/2, datas[0]["val"], width, label=datas[0]["label"])
rects2 = ax.barh(x + width/2, datas[1]["val"], width, label=datas[1]["label"])
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_yticks(x)
ax.set_yticklabels(labels)
plt.gca().invert_yaxis()
Die Verwendung ist wie folgt.
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
datas = [
{"label": "men1", "val": [20, 34, 30, 35, 27]},
{"label": "women2", "val": [25, 32, 34, 20, 25]}]
fig, ax = plt.subplots()
# barhplot(ax, labels, datas)
barplot(ax, labels, datas)
plt.legend()
plt.show()
barplot
barhplot
Bei 3 oder mehr ist es notwendig, die Breite anzupassen und anzuordnen.
Recommended Posts