mehh
mehh

Reputation: 59

MultiIndexing and plotting using pandas

I would like to plot this pandas DataFrame as three 2D lines: no_transfer, transfer and random_transfer, where each respective line is from the columns 0 to 9. The DataFrame has a MultiIndex. I'd also like to get rid of the "is_greedy" level since the value is the same for all.

                              0    1     2     3  ...      6     7     8     9
config          is_greedy                         ...                         
no_transfer     True        9.0  9.0  14.0  15.0  ...   16.5  15.0  11.0   9.5
transfer        True        9.0  9.5  27.5  10.5  ...   19.5  55.5  14.0  24.0
random_transfer True       35.5  9.0  13.5  10.0  ...   10.0  13.0  27.5  32.0

Upvotes: 0

Views: 71

Answers (1)

ALollz
ALollz

Reputation: 59529

Drop the index level, transpose and plot.

df.reset_index('is_greedy', drop=True).T.plot()

Sample Data

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(30, 50, (3, 11)), 
                  index=['no_transfer', 'transfer', 'random_transfer'])
df = df.set_index(10, append=True)
df.index.names=['config', 'is_greedy']
#                            0   1   2   3   4   5   6   7   8   9
#config          is_greedy                                        
#no_transfer     40         35  49  47  36  48  47  39  48  38  32
#transfer        33         35  33  45  38  38  45  36  30  46  36
#random_transfer 36         32  41  36  41  37  35  40  42  49  32

df.reset_index('is_greedy', drop=True).T.plot()

enter image description here


Or iterate through the rows:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
for idx, row in df.iterrows():
    ax.plot(df.columns, row, label=idx[0])
plt.legend()
plt.show()

Upvotes: 2

Related Questions