Search code examples
pythonpandasmatplotlibseabornmulti-index

Plotting pandas multi-index DataFrame with one index as Y-axis and other as X-axis


I have a multi-index dataframe that is sampled here:

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline

df = pd.read_csv('https://docs.google.com/uc?id=1mjmatO1PVGe8dMXBc4Ukzn5DkkKsbcWY&export=download', index_col=[0,1])

df

enter image description here

I tried to plot this so that each column ['Var1', 'Var2', 'Var3', 'Var4'] in a separate figure, the Country is a curve, and y-axis, and the Year is the x-axis

the requested figure would be like this Ms-Excel figure

enter image description here

I tried to plot it using

f, a = plt.subplots(nrows=2, ncols=2, figsize=(9, 12), dpi= 80)

df.xs('Var1').plot(ax=a[0])
df.xs('Var2').plot(ax=a[1])
df.xs('Var3').plot(x=a[2])
df.xs('Var4').plot(kax=a[3])

but it gives KeyError: 'Var1'

I also tried the following

f, a = plt.subplots(nrows=2, ncols=2, 
                              figsize=(7, 10), dpi= 80)
for indicator in indicators_list:
    for c, country in enumerate(in_countries):
        ax = df[indicator].plot()
        ax.title.set_text(country + " " + indicator) 

but it returns 3 empty figures and one figure with all the data in it enter image description here

What is wrong with my trials and What can I do to get what I need?


Solution

  • If I understand correctly you should first pivot your dataframe in order to have countries as columns:

    In [151]: df.reset_index().pivot('Year','Country','Var1').plot(ax=a[0,0], title='Var1', grid=True)
    Out[151]: <matplotlib.axes._subplots.AxesSubplot at 0x127e2320>
    
    In [152]: df.reset_index().pivot('Year','Country','Var2').plot(ax=a[0,1], title='Var2', grid=True)
    Out[152]: <matplotlib.axes._subplots.AxesSubplot at 0x12f47b00>
    
    In [153]: df.reset_index().pivot('Year','Country','Var3').plot(ax=a[1,0], title='Var3', grid=True)
    Out[153]: <matplotlib.axes._subplots.AxesSubplot at 0x12f84668>
    
    In [154]: df.reset_index().pivot('Year','Country','Var4').plot(ax=a[1,1], title='Var4', grid=True)
    Out[154]: <matplotlib.axes._subplots.AxesSubplot at 0x12fbd390>
    

    Result:

    enter image description here