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

后端 未结 9 810
不知归路
不知归路 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:44

    Use plt.text() to put text in the plot.

    Example:

    import matplotlib.pyplot as plt
    N = 5
    menMeans = (20, 35, 30, 35, 27)
    ind = np.arange(N)
    
    #Creating a figure with some fig size
    fig, ax = plt.subplots(figsize = (10,5))
    ax.bar(ind,menMeans,width=0.4)
    #Now the trick is here.
    #plt.text() , you need to give (x,y) location , where you want to put the numbers,
    #So here index will give you x pos and data+1 will provide a little gap in y axis.
    for index,data in enumerate(menMeans):
        plt.text(x=index , y =data+1 , s=f"{data}" , fontdict=dict(fontsize=20))
    plt.tight_layout()
    plt.show()
    

    This will show the figure as:

    bar chart with values at the top

提交回复
热议问题