繁体   English   中英

matplotlib 向特定条形添加值,但不添加高度

[英]matplotlib adding values to specific bars, but not the height

我的 DF 看起来像这样:

ID    Ctg     Value_1   Result_1    Result_2     Result_3
1     Car     0.5       100         105          80
2     Bike    0.35      200         150          130 
3     Plane   0.51      45          70           77
4     Car     ...       ...         ...          ... 
5     Plane   ...       ...         ...          ... 
6     Plane   ...       ...         ...          ...  
7     Bike    ...       ...         ...          ... 
8     Car     ...       ...         ...          ... 
9     Car     ...       ...         ...          ... 
distinct_Ctg = data.Ctg.unique()

for loop_count, i in enumerate(distinct_Ctg):
    
    # Subset for each category
    data_graph_sub = data.loc[data['Ctg'] == i]
    
    X = np.arange(len(data_graph_sub ))
    fig = plt.figure()
    ax = fig.add_axes([0,0,1,1])
    ax.set_facecolor('#E6E6E6')
    bar_1 = ax.bar(X - 0.25, data_graph_sub['Result_1'], color = 'steelblue', width = 0.25) 
    bar_2 = ax.bar(X, data_graph_sub['Result_2'], color = 'orange', width = 0.25)
    bar_3 = ax.bar(X + 0.25, data_graph_sub['Result_3'], color = 'indianred', width = 0.25)
    
    plt.ylabel('Unit')
    plt.title(i +': This is my title')
    plt.grid(color='w', linestyle='solid')
    for spine in ax.spines.values():
        spine.set_visible(False)
    ax.set_axisbelow(True)    
    ax.set_xticks(X) 
    ax.set_xticklabels(data_graph_sub.ID, rotation = 40, fontsize = 'small', ha = 'right')
    ax.xaxis.tick_bottom()
    ax.yaxis.tick_left()
    
   
    blue_patch = mpatches.Patch(color='steelblue', label='Result from Programm 1')
    green_patch = mpatches.Patch(color='orange', label='Result from Programm 2')
    red_patch = mpatches.Patch(color='indianred', label='Result from Programm 3')
    plt.legend(handles = [blue_patch, green_patch, red_patch])
    
    # plt.show()
    
    plt.savefig(r'graphs/' + str(loop_count) + '.png', bbox_inches='tight', pad_inches=0)

有了这个,我为 Ctg 中的每种类型创建了一个图形,到目前为止,结果对我来说看起来不错。

我现在想将我的 DF 中的 Value_1 添加到三个条形图之一(添加到来自 data_graph_sub ['Result_1'] 的钢蓝条形图),如下所示: https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/ barchart.html ,但在此示例中,该值是条形的高度,并且绘制到所有条形。

我怎么能意识到这一点?

编辑:我添加了这个,但它还不正确......

for z in bar_1:
    plt.text(z.get_x(), z.get_height(), data_graph_sub['Value_1'], size = 10)

如何将特定栏链接到 data_graph_sub['Value_1'] 中的正确值?

使用 zip 您可以同时循环遍历条形和值:

for bar, val in zip(bar_1, data_graph_sub['Value_1']):
    ax.text(bar.get_x() + bar.get_width()/2, bar.get_height(), f'{val:0.2f}\n', 
            size=10, ha='center', va='center')

暂无
暂无

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

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