pythonpandasmatplotlibseaborn

Making several pieplots from dataframe columns


I made a dataframe from some data that looks like the following

df = pd.Dataframe({'Keys': ['key1','key2','key3']
                   'Percentage':[63,37,89]}

I want to create 3 piecharts that show the percentage for each key. Thought it was going to be easy but all I could find was how to create a chart that contains all 3 keys.

The quick way to fix it would be to create some lists for every key and make the chart based on that but is it there a way to do this more efficiently?

Edit:

I'd like to create something like this for each key

import matplotlib.pyplot as plt

fig1, ax1 = plt.subplots()
labels = ['key1_yes','key1_no']
sizes = [63,37]

ax1.set_title('key1')

ax1.pie(sizes, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90)

Solution

  • If you define your df as follows:

    import pandas as pd
    
    df = pd.DataFrame({'key': ['key1', 'key1', 'key2', 'key2', 'key3', 'key3'],
                       'kind': ['yes', 'no', 'yes', 'no', 'yes', 'no'],
                       'n': [63, 37, 89, 11, 37, 63]})
    df
        key kind   n
    0  key1  yes  63
    1  key1   no  37
    2  key2  yes  89
    3  key2   no  11
    4  key3  yes  37
    5  key3   no  63
    

    then you can plot like this:

    import matplotlib.pyplot as plt
    import seaborn as sns
    
    def my_pie(n, kind, **kwargs):
        plt.pie(x = n, labels = kind)
    
    g = sns.FacetGrid(df, col = 'key')
    g.map(my_pie, 'n', 'kind')
    

    which yields

    enter image description here