![](/img/trans.png)
[英]How to write text inside the bar in a horizontal bar graph matplotlib?
[英]Python: How to put text vertically inside bar graph using Matplotlib
我想將我的文本垂直放在條形圖中。 我嘗試過,但無法抓住它。
import pandas as pd
import matplotlib.pyplot as plt
dataF = pd.DataFrame({
'date':['12 Jul, 15','30 Aug, 17','23 Dec,19','12 Mar,21'],
'revenue':[34,25,30,38],
'status':['PAID','NOT PAID','PAID','NOT PAID']
})
print(dataF)
date revenue status
0 12 Jul, 15 34 PAID
1 30 Aug, 17 25 NOT PAID
2 23 Dec,19 30 PAID
3 12 Mar,21 38 NOT PAID
plt.close('all')
plt.rcParams['figure.figsize']=(10,6)
fig,ax = plt.subplots()
rects = ax.bar(dataF['date'], dataF['revenue'],
width=0.2, color = 'orange')
def autolabel(rects):
for rect in rects:
h = rect.get_height()
ax.text(rect.get_x()+rect.get_width()/2., 1.02*h,
str(''), ha='center', va='bottom')
autolabel(rects)
plt
現在,我希望status
垂直顯示在條內,就像我在下面手動所做的那樣。
像這樣用換行符加入字符串怎么樣
'\n'.join(status)
總共像
fig, ax = plt.subplots()
rects = ax.bar('date', 'revenue', width=0.2, color='orange', data=dataF)
for status, r in zip(dataF['status'], rects):
ax.text(r.get_x() + r.get_width()/2., 0.95 * r.get_height(),
'\n'.join(status), ha='center', va='top')
matplotlib 3.4.0
從matplotlib 3.4.0
開始,您可以使用axes.bar_label
以更簡潔的方式自動實現類似的效果
fig, ax = plt.subplots()
rects = ax.bar('date', 'revenue', width=0.2, color='orange', data=dataF)
ax.bar_label(rects, ('\n'.join(i) for i in dataF["status"]), label_type='center')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.