如何在matplotlib条形图中的条形上方显示Y值?

时间:2020-07-26 12:51:10

标签: python matplotlib bar-chart

我正在从数据框中生成条形图,我想删除Y轴标签并将其显示在条形上方。我该如何实现?
到目前为止,这是我的代码:

ax = rounded_df.plot(kind='bar',
                     figsize=(20, 8),
                     width=0.8,
                     color=['#5cb85c', '#5bc0de', '#d9534f']
                     )
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.legend(fontsize=14)
plt.title('Percentage of Respodents\' Interest in Data Science Areas', fontsize=16)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)

以下是我的图表: Graph

这是数据:

                            Very_interested Somewhat_interested Not_interested
Data_Analysis/Statistics    72.95           21.36               3.31
Machine_Learning            75.59           19.88               2.69
Data_Visualization          60.01           32.87               4.57
Big_Data_(Spark/Hadoop)     59.65           32.65               5.69
Deep_Learning               56.56           34.48               6.09
Data_Journalism             19.21           48.41               27.32

1 个答案:

答案 0 :(得分:0)

使用ax.patches可以实现。

这可以做到:

for p in ax.patches:
        ax.annotate(str(round(p.get_height(),2)), (p.get_x() * 1.005, p.get_height() * 1.005),color='green')

尝试:

样本数据:

    1q1         1q2         1q3         1q4
Cust / Month                
AA  62264.65    103189.45   94989.70    86212.37
AB  3330.47     0.00        0.00        0.00
AC  36580.00    36113.10    37527.84    32241.18
AD  36803.13    0.00        0.00        0.00
AE  44200.66    0.00        0.00        0.00
AF  12971.52    13697.76    13257.60    11931.84

示例代码:

customer_count = [38.00, 30.00, 30.00, 20.00]

ax = res.T.plot(width=0.8, kind='bar',y=['Quarter Total'],figsize=(10,5))
for rect, value in zip(ax.patches, customer_count):
    if value != 0:
        h = rect.get_height() /2.
        w = rect.get_width() /2.
        x, y = rect.get_xy()
        ax.text(x+w, y+h,value, horizontalalignment='center', verticalalignment='center', color='white',rotation=0)

for p in ax.patches:
    ax.annotate(str(round(p.get_height(),2)), (p.get_x() * 1.005, p.get_height() * 1.005),color='green')
    
plt.title('expediture data Quarter Wise')

enter image description here



df:

    a   b   c   d
a1  66  92  98  17
a2  83  57  86  97
a3  96  47  73  32

ax = df.T.plot(width=0.8, kind='bar',y=df.columns,figsize=(10,5))
for p in ax.patches:
    ax.annotate(str(round(p.get_height(),2)), (p.get_x() * 1.005, p.get_height() * 1.005),color='green')
  
ax.axes.get_yaxis().set_ticks([])

enter image description here