简体   繁体   中英

Drawing a percentage bar chart in python

I am looking present the information about the proportion of students getting different grades, and I am trying to avoid using a pie chart. Instead, the following style seemed appealing to me:

在此处输入图像描述

Is there any way to achieve something like this visualisation in matplotlib or adjacent libraries? I know I can use barh() for a horizontal bar, but really an ideal solution would be able to do away with the axes here since the y axis is not necessary here, at the least.

You can use pandas.DataFrame.plot.barh to make a horizontal single stacked bar. For the example, I used one of the datasets similar to yours that I found in the Office of National Statistics to show you the general logic.

Try this:

import pandas as pd
import requests

url= "https://www.ons.gov.uk/file?uri=/peoplepopulationandcommunity/populationandmigration/populationestimates/bulletins/annualmidyearpopulationestimates/mid2018/fa9e61d4.xlsx"

excel_file = requests.get(url)

ages_labels = ["0-14yrs", "15-64yrs", "65yrs+"]

def set_categories(df):
    df["Category"]= pd.qcut(x= df.pop("Age"), q=[0, 0.16, 0.73, 1], labels=ages_labels)
    return df

(
    pd.read_excel(excel_file.content, header=2, usecols="A:B")
        .apply(pd.to_numeric, errors="coerce")
        .dropna()
        .pipe(set_categories)
        .groupby("Category").sum()
        .transpose()
        .plot.barh(
            stacked= True,
            width= 0.1,
            color= ["#3d8881", "#2b7dc0", "#d2417e"],
            figsize=(7, 3))
)

# Output:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM