这可以通过使用@Evan在此评论中链接的示例来实现,即
this one
. 重要的一点是名为
autolabel
在链接的示例中。将显示的值从y轴值更改为x轴值很容易,请替换
height
具有
rect.get_x()
. 更棘手的是将值放在条的顶部。通过对数据框中的值求和,可以找到条的总高度。
heights = df_select.iloc[:,:].sum(axis=1)
然后需要将其传递给autolabel函数,并用作条形图的高度。可以使用删除x记号标签
ax.get_xaxis().set_ticklabels([])
您可以在特定站点的x轴下方添加更多文本,只需使用
ax.text
使用的内容
sites
作为x位置,并将y位置设置为低于轴(-0.5或其他)。
综上所述,我们得到以下工作示例:
def autolabel(rects, heights):
"""
Attach a text label above each bar displaying its height
Modified for use with a stacked bar chart
"""
for i, rect in enumerate(rects):
x = rect.get_x()
wid = rect.get_width()
height = heights.values[i]
ax.text(x + wid/2., 1.05*height,
'%d' % (int(x) + int((wid/2)+0.5)),
ha='center', va='bottom', rotation=90)
df = pd.DataFrame(np.random.randint(1, 5, size=(3200, 3)))
df.loc[np.random.choice(df.index, size=3190, replace=False), :] = 0
df_select = df[df.sum(axis=1)>1]
fig, ax = plt.subplots()
ax.bar(df_select.index, df_select.iloc[:,0], label = df_select.columns[0], width = 15)
if df_select.shape[1] > 1:
for i in range(1, df_select.shape[1]):
bottom = df_select.iloc[:,np.arange(0,i,1)].sum(axis=1)
rects1 = ax.bar(df_select.index, df_select.iloc[:,i], bottom=bottom, label =
df_select.columns[i], width = 15)
ax.set_xticks(df_select.index)
ax.get_xaxis().set_ticklabels([]) # turn off the x tick labels
plt.legend(loc='best', bbox_to_anchor=(1, 0.5))
heights = df_select.iloc[:, :].sum(axis=1)
autolabel(rects1, heights)
# Select 3 random value to add labels below the x axis. Make sure they are
# within the axis limits
sites = np.random.choice(df_select.index, 3)
for site in sites:
ax.text(site, -0.5,
'site(%s)' % site,
ha='center', va='bottom',fontsize=6)
plt.show()
给出了以下图表:
注:
这有时看起来很凌乱,因为这些条非常细且分散,并且可以彼此靠近,这意味着值可能开始重叠。