Search code examples
pythonpandaspie-chart

how to plot a pie chart row wise?


If the data is like:

one two
123456 98765
456767 45678
123454 87654

Then how a pie chart can be formed for say 1st row values ie values 123456 ,98765in pandas ?

I tried codes which are given on internet as:

df.T.plot.pie(subplots=True, figsize=(9, 3))

and

import matplotlib.pyplot as plt

df.Data.plot(kind='pie')

fig = plt.figure(figsize=(6,6), dpi=200)
ax = plt.subplot(111)

df.Data.plot(kind='pie', ax=ax, autopct='%1.1f%%', startangle=270, fontsize=17)

but these codes don't plot row values instead giving a cloumn result.


Solution

  • If you want to get row-wise pie plots, you can iterate the rows and plot each row:

    In [1]: import matplotlib.pyplot as plt
       ...: import pandas as pd
       ...: import seaborn as sns
       ...:
       ...: sns.set(palette='Paired')
       ...: %matplotlib inline
    
    In [2]: df = pd.DataFrame(columns=['one', 'two'], data=[[123456, 98765],[456767, 45678],[123454, 87654]])
    
    In [3]: df.head()
    Out[3]:
          one    two
    0  123456  98765
    1  456767  45678
    2  123454  87654
    
    In [4]: for ind in df.index:
       ...:     fig, ax = plt.subplots(1,1)
       ...:     fig.set_size_inches(5,5)
       ...:     df.iloc[ind].plot(kind='pie', ax=ax, autopct='%1.1f%%')
       ...:     ax.set_ylabel('')
       ...:     ax.set_xlabel('')
       ...:
    <matplotlib.figure.Figure at 0x1e8b4205c50>
    <matplotlib.figure.Figure at 0x1e8b41f56d8>
    <matplotlib.figure.Figure at 0x1e8b4437438>
    

    Row-wise pie plots

    EDIT:

    To plot only a specific row, you are selecting with .iloc the row you want to plot (e.g., row 0).

    fig, ax = plt.subplots(1,1)
    fig.set_size_inches(5,5)
    df.iloc[0].plot(kind='pie', ax=ax, autopct='%1.1f%%')
    ax.set_ylabel('')
    ax.set_xlabel('')
    

    See documentation on Indexing and Selecting Data