MatplotLib - 更改 y 轴并显示数据标签

MatplotLib - change y axis and show data labels

我想更改我的 y 轴,使其显示 0、25、50、75 和 100。此外,我如何在每个条上显示数据标签?我尝试使用 ylim 但它不起作用。

group_a = (a,b,c,d,e)
group_b = (f,g,h,i,j)
group_c = (k,l,m,n,o)
width = 0.2
x = np.arange(5)
plt.bar(x-0.2, group_a, width, color = 'cyan')
plt.bar(x, group_b, width, color = 'orange')
plt.bar(x+0.2, group_c, width, color = 'green')
plt.xticks(x, ['1','2','3','4','5'])
plt.xlabel("quarter")
plt.ylabel('%')
plt.legend(['Group A','Group B','Group C'])
plt.show()

plt.yticks 设置为所需的值。

Additionally, how can I show the data labels over each bar?

我不太确定我是否正确理解了您想要的内容。看看下面,在评论中让我知道。

import numpy as np
import matplotlib.pyplot as plt
a,b,c,d,e,f,g,h,i,j,k,l,m,n,o = np.random.randint(0, 100, 15)
group_a = (a,b,c,d,e)
group_b = (f,g,h,i,j)
group_c = (k,l,m,n,o)
width = 0.2
offset_y = 2
x = np.arange(5)
plt.figure()
plt.bar(x-0.2, group_a, width, color = 'cyan')
plt.bar(x, group_b, width, color = 'orange')
plt.bar(x+0.2, group_c, width, color = 'green')
for _x, t in zip(x, group_a):
    plt.text(_x-0.2, t + offset_y, str(t), horizontalalignment="center")
for _x, t in zip(x, group_b):
    plt.text(_x, t + offset_y, str(t), horizontalalignment="center")
for _x, t in zip(x, group_c):
    plt.text(_x+0.2, t + offset_y, str(t), horizontalalignment="center")
plt.xticks(x, ['1','2','3','4','5'])
plt.xlabel("quarter")
plt.yticks(np.linspace(0, 100, 5, dtype=int))
plt.ylabel('%')
plt.legend(['Group A','Group B','Group C'])
plt.show()