Search code examples
pythonpandasplotmulti-index

Plotting multi indexed data with pandas


I have a Python dictionary in the form of:

dict = {0: {a: 1, b: 2}, 1: {a: 1, b: 2}}

I created a Pandas DataFrame from it, by using from_dict(). This gave me a multiindex dataframe`, as expected.

Now I want to plot this dataframe with the outer index being the x-axis and the inner index being separate lines in my graph, the data points on the y-axis being the values.

I tried stacking them, but it only gave me a single line.

My current code:

data = pd.DataFrame.from_dict(my_data)
data = data.T.stack()
data.plot()

Anyone has an idea how this could be done?


Solution

  • Use

    data.groupby(level=1).plot(stacked=True)
    

    import pandas as pd
    import matplotlib.pyplot as plt
    
    my_data = {0: {'a': 1, 'b': 2}, 1: {'a': 1, 'b': 2}}
    data = pd.DataFrame.from_dict(my_data)
    data = data.T.stack()
    # 0  a    1
    #    b    2
    # 1  a    1
    #    b    2
    # dtype: int64
    
    data.groupby(level=1).plot(stacked=True, legend=True)
    plt.show()
    

    Or, for more control in configuring the plot it may be easier to use matplotlib directly:

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    
    data = pd.concat({key:pd.Series(np.random.randint(10, size=(10,))) for key in 'AB'}).swaplevel()
    
    fix, ax = plt.subplots()
    for key, grp in data.groupby(level=1):
        ax.plot(grp.index.get_level_values(0), grp.values, label=key)
    plt.legend()
    plt.plot()
    plt.show()
    

    enter image description here