如何使用 python matplotlib 的艺术家层在条形图上显示百分比值

Min*_*ary 2 python label bar-chart

在过去的 3 天里,我一直试图将每个条形的百分比值放在图上,但没有用!!

在此处输入图片说明

df_ds.sort_values('Very interested', ascending = False)
df_dsp = ((100*df_ds / 2233).round(2).astype(str) + '%')

#PLOTTING
ax1 = df_ds.plot(kind = 'bar',
                figsize = (20,8),
                width = 0.8,
                color = ('#5cb85c', '#5bc0de', '#d9534f'),
                fontsize = 14)
ax1.set_title("Percentage of Respondents' Interest in Data Science", fontsize = 16)
ax1.legend(fontsize = 14)
ax1.spines['top'].set_visible(False)
ax1.spines['right'].set_visible(False)
ax1.spines['left'].set_visible(False)
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以使用patchesfrom matplotlib,并使用get_x()get_height()获取百分比值的坐标。假设我们已经导入了你的数据框,你的代码就变成了

import pandas as pd
import matplotlib.pyplot as plt

# Assuming that we imported df_ds...
df_ds.sort_values('Very interested', ascending = False)

# Formatting to a percentage will be done in the plotting
df_dsp = df_ds / 2233

#PLOTTING
ax1 = df_ds.plot(kind = 'bar',
                figsize = (20,8),
                width = 0.8,
                color = ('#5cb85c', '#5bc0de', '#d9534f'),
                fontsize = 14)
ax1.set_title("Percentage of Respondents' Interest in Data Science", 
             fontsize = 16)
ax1.legend(fontsize = 14)
ax1.spines['top'].set_visible(False)
ax1.spines['right'].set_visible(False)
ax1.spines['left'].set_visible(False)

# Adding the percentage values    
for p in ax1.patches:
    ax1.annotate("{:.2%}".format(p.get_height()),
                xy=(p.get_x()+0.02, p.get_height()+0.01))
Run Code Online (Sandbox Code Playgroud)

其中最后两行是百分比值的代码。结果如下所示:

在此处输入图片说明