python条形堆积图_python – 使用DataFrame.plot显示堆积条形图中...
您可以使用plt.text根據數據將信息放在位置.
但是,如果你有非常小的條形,可能需要一些調整才能看起來很完美.
df_total = df['Total Cost']
df = df.iloc[:, 0:4]
df.plot(x = 'Airport', kind='barh',stacked = True, title = 'Breakdown of Costs', mark_right = True)
df_rel = df[df.columns[1:]].div(df_total, 0)*100
for n in df_rel:
for i, (cs, ab, pc, tot) in enumerate(zip(df.iloc[:, 1:].cumsum(1)[n], df[n], df_rel[n], df_total)):
plt.text(tot, i, str(tot), va='center')
plt.text(cs - ab/2, i, str(np.round(pc, 1)) + '%', va='center', ha='center')
編輯:一些任意想法,以提高可讀性:
將總值向右移動,使用45°旋轉文本:
plt.text(tot+10000, i, str(tot), va='center')
plt.text(cs - ab/2, i, str(np.round(pc, 1)) + '%', va='center', ha='center', rotation=45)
在頂部和底部對齊的文本之間切換:
va = ['top', 'bottom']
va_idx = 0
for n in df_rel:
va_idx = 1 - va_idx
for i, (cs, ab, pc, tot) in enumerate(zip(df.iloc[:, 1:].cumsum(1)[n], df[n], df_rel[n], df_total)):
plt.text(tot+10000, i, str(tot), va='center')
plt.text(cs - ab/2, i, str(np.round(pc, 1)) + '%', va=va[va_idx], ha='center')
僅標記10%或更多的條形:
if pc >= 10:
plt.text(cs - ab/2, i, str(np.round(pc, 1)) + '%', va='center', ha='center')
…或仍然打印它們,但垂直:
if pc >= 10:
plt.text(cs - ab/2, i, str(np.round(pc, 1)) + '%', va='center', ha='center')
else:
plt.text(cs - ab/2, i, str(np.round(pc, 1)) + '%', va='center', ha='center', rotation=90)
總結
以上是生活随笔為你收集整理的python条形堆积图_python – 使用DataFrame.plot显示堆积条形图中...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中国二十四节气的意义(二十四节气的具体内
- 下一篇: ddu卸载显卡驱动下载安装教程