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

后端 未结 9 791
不知归路
不知归路 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')
    

提交回复
热议问题