How to display the value of the bar on each bar with pyplot.barh()?

后端 未结 9 667
不知归路
不知归路 2020-11-22 08:10

I generated a bar plot, how can I display the value of the bar on each bar?

Current plot:

\"enter

相关标签:
9条回答
  • 2020-11-22 08:47

    I needed the bar labels too, note that my y-axis is having a zoomed view using limits on y axis. The default calculations for putting the labels on top of the bar still works using height (use_global_coordinate=False in the example). But I wanted to show that the labels can be put in the bottom of the graph too in zoomed view using global coordinates in matplotlib 3.0.2. Hope it help someone.

    def autolabel(rects,data):
    """
    Attach a text label above each bar displaying its height
    """
    c = 0
    initial = 0.091
    offset = 0.205
    use_global_coordinate = True
    
    if use_global_coordinate:
        for i in data:        
            ax.text(initial+offset*c, 0.05, str(i), horizontalalignment='center',
                    verticalalignment='center', transform=ax.transAxes,fontsize=8)
            c=c+1
    else:
        for rect,i in zip(rects,data):
            height = rect.get_height()
            ax.text(rect.get_x() + rect.get_width()/2., height,str(i),ha='center', va='bottom')
    

    0 讨论(0)
  • 2020-11-22 08:49

    Add:

    for i, v in enumerate(y):
        ax.text(v + 3, i + .25, str(v), color='blue', fontweight='bold')
    

    result:

    enter image description here

    The y-values v are both the x-location and the string values for ax.text, and conveniently the barplot has a metric of 1 for each bar, so the enumeration i is the y-location.

    0 讨论(0)
  • 2020-11-22 08:49

    Check this link Matplotlib Gallery This is how I used the code snippet of autolabel.

        def autolabel(rects):
        """Attach a text label above each bar in *rects*, displaying its height."""
        for rect in rects:
            height = rect.get_height()
            ax.annotate('{}'.format(height),
                        xy=(rect.get_x() + rect.get_width() / 2, height),
                        xytext=(0, 3),  # 3 points vertical offset
                        textcoords="offset points",
                        ha='center', va='bottom')
            
    temp = df_launch.groupby(['yr_mt','year','month'])['subs_trend'].agg(subs_count='sum').sort_values(['year','month']).reset_index()
    _, ax = plt.subplots(1,1, figsize=(30,10))
    bar = ax.bar(height=temp['subs_count'],x=temp['yr_mt'] ,color ='g')
    autolabel(bar)
    
    ax.set_title('Monthly Change in Subscribers from Launch Date')
    ax.set_ylabel('Subscriber Count Change')
    ax.set_xlabel('Time')
    plt.show()
    
    0 讨论(0)
提交回复
热议问题