简体   繁体   中英

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.

在此处输入图像描述

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

Since matplotlib 3.4.0 you can use axes.bar_label to automatically achieve a similar effect in a much cleaner way

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在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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