简体   繁体   English

Python:如何使用 Matplotlib 在条形图中垂直放置文本

[英]Python: How to put text vertically inside bar graph using Matplotlib

I want to put my text vertically inside the bar graph.我想将我的文本垂直放在条形图中。 I tried, but couldn't get hold of it.我尝试过,但无法抓住它。

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

Now, I want the status to appear inside the bars vertically, just as I did manually below.现在,我希望status垂直显示在条内,就像我在下面手动所做的那样。

在此处输入图像描述

How about joining the string with newlines like so像这样用换行符加入字符串怎么样

'\n'.join(status)

In total something like总共像

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')

Gives在此处输入图像描述

Edit: matplotlib 3.4.0编辑: matplotlib 3.4.0

Since matplotlib 3.4.0 you can use axes.bar_label to automatically achieve a similar effect in a much cleaner waymatplotlib 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')

produces生产在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM