如何使用matplotlib修复条形图中的改写值?

时间:2018-08-02 19:15:10

标签: python-3.x pandas matplotlib

我想使用matplotlib绘制数据框,其值超过条形:

enter image description here

但是,就我而言,这些值被覆盖了

enter image description here

考虑到这一点,我有两个疑问:

  1. 如何在每个条形上清楚地放置百分比值?
  2. 如何水平放置x轴值,日期?

我的代码:

  view = df_esc[['data_semana', 'porcentagem']].set_index('data_semana')
    del view.index.name

    ax = view.plot(kind='bar', figsize=(16,4),
                                            color="steelblue", fontsize=12)
    ax.set_alpha(0.8)
    ax.set_title("Porcentagem de professores que avaliaram", fontsize=18)
    ax.set_ylabel("% Professores", fontsize=12);
    ax.set_yticks(df_esc['porcentagem'].tolist())

    # create a list to collect the plt.patches data
    totals = []

    # find the values and append to list
    for i in ax.patches:
        totals.append(i.get_height())

    # set individual bar lables using above list
    total = sum(totals)

    # set individual bar lables using above list
    for i in ax.patches:
        for v in df_esc['porcentagem'].tolist(): 
            # get_x pulls left or right; get_height pushes up or down
            ax.text(i.get_x()+.12, i.get_height()-3, str(v) + 'str', fontsize=18, color='white')

我遵循了this的示例。

1 个答案:

答案 0 :(得分:0)

要遍历两个循环,我使用了zip

解决方案

view = df_esc[['data_semana', 'porcentagem']].set_index('data_semana')
del view.index.name

ax = view.plot(kind='bar', figsize=(16,4),
                                        color="steelblue", fontsize=12)
ax.set_alpha(0.8)
ax.set_title("Porcentagem de professores que avaliaram", fontsize=18)
ax.set_ylabel("% Professores", fontsize=12);
ax.set_yticks(df_esc['porcentagem'].tolist())

# create a list to collect the plt.patches data
totals = []

# find the values and append to list
for i in ax.patches:
    totals.append(i.get_height())

# set individual bar lables using above list
total = sum(totals)

# set individual bar lables using above list
for i, v in zip(ax.patches, df_esc['porcentagem'].tolist()):
    # get_x pulls left or right; get_height pushes up or down
    ax.text(i.get_x()+.14, i.get_height()+1, str(v) + '%', fontsize=12, color='gray')