Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show values inside the bars of a bargraph?

I have a dataframe like this:

                 platform     count
release_year        
         1996    PlayStation   138
         1997    PlayStation   170
         1998    PlayStation   155
         1999    PC            243...

Now I want to plot horizontal bargraph with the Platform name inside the respective bars such that it looks something like this:

enter image description here

How do I do that?

like image 824
user517696 Avatar asked Dec 03 '22 22:12

user517696


1 Answers

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")

enter image description here

like image 54
David Jaimes Avatar answered Jan 12 '23 00:01

David Jaimes