除了计数之外,我想将百分比值添加到我的熊猫程序中。但是,我无法这样做。我的代码如下所示,到目前为止,我可以显示计数值。有人可以帮我在每个条显示的计数值旁边/下方添加相对%值吗?
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('ggplot')
import seaborn as sns
sns.set_style("white")
fig = plt.figure()
fig.set_figheight(5)
fig.set_figwidth(10)
ax = fig.add_subplot(111)
counts = [29227, 102492, 53269, 504028, 802994]
y_ax = ('A','B','C','D','E')
y_tick = np.arange(len(y_ax))
ax.barh(range(len(counts)), counts, align = "center", color = "tab:blue")
ax.set_yticks(y_tick)
ax.set_yticklabels(y_ax, size = 8)
#annotate bar plot with values
for i in ax.patches:
ax.text(i.get_width()+.09, i.get_y()+.3, str(round((i.get_width()), 1)), fontsize=8)
sns.despine()
plt.show();
答案 0 :(得分:2)
fig = plt.figure()
fig.set_figheight(5)
fig.set_figwidth(10)
ax = fig.add_subplot(111)
counts = [29227, 102492, 53269, 504028, 802994]
# calculate percents
percents = [100*x/sum(counts) for x in counts]
y_ax = ('A','B','C','D','E')
y_tick = np.arange(len(y_ax))
ax.barh(range(len(counts)), counts, align = "center", color = "tab:blue")
ax.set_yticks(y_tick)
ax.set_yticklabels(y_ax, size = 8)
#annotate bar plot with values
for i, y in enumerate(ax.patches):
label_per = percents[i]
ax.text(y.get_width()+.09, y.get_y()+.3, str(round((y.get_width()), 1)), fontsize=10)
# add the percent label here
# ax.text(y.get_width()+.09, y.get_y()+.3, str(round((label_per), 2)), ha='right', va='center', fontsize=10)
ax.text(y.get_width()+.09, y.get_y()+.1, str(f'{round((label_per), 2)}%'), fontsize=10)
sns.despine()
plt.show();
\n
,以获得“自然”的行距:str(f'{round((y.get_width()), 1)}\n{round((label_per), 2)}%')
ax.text(..., va='center')
垂直居中,并可以使用稍大的字体。 ax.set_xlim(0, max(counts) * 1.18)
来获得更多的文本空间。 str(f' {round((label_per), 2)}%')
,请注意{
之前的空格。y.get_width()+.09
非常接近y.get_width()
。