How to show values inside the bars of a bargraph?

前端 未结 2 901
星月不相逢
星月不相逢 2021-01-06 10:01

I have a dataframe like this:

                 platform     count
release_year        
         1996    PlayStation   138
         1997    PlayStation   170
         


        
2条回答
  •  灰色年华
    2021-01-06 10:34

    Here's the input data.csv file once you find the percentage in each platform:

    Platform,Percent
    Nintendo,34
    PC,16
    Playstation,28
    Xbox,22
    

    This is the code:

    import pandas as pd
    import matplotlib.pyplot as plt
    
    df = pd.read_csv("data.csv", index_col=0)
    df.plot(kind="barh", legend=False, width=0.8)
    for i, (p, pr) in enumerate(zip(df.index, df["Percent"])):
        plt.text(s=p, x=1, y=i, color="w", verticalalignment="center", size=18)
        plt.text(s=str(pr)+"%", x=pr-5, y=i, color="w",
                 verticalalignment="center", horizontalalignment="left", size=18)
    plt.axis("off")
    # xticks & yticks have empty lists to reduce white space in plot
    plt.xticks([])
    plt.yticks([])
    plt.tight_layout()
    plt.savefig("data.png")
    

提交回复
热议问题