DavideC
DavideC

Reputation: 1

Plotting two pandas dataframe columns against each other in multiindex

Let's say, we have a pandas DataFrame:

df = pd.DataFrame(np.array([[1,2,3,4,5],[3,4,5,6,7]]).T, columns=['a','b'])

print(df)

which gives me:

   a  b
0  1  3
1  2  4
2  3  5
3  4  6
4  5  7

if I try to plot column 'a' on column 'b', I can very simply do:

df.plot(x='a', y='b')
plt.show()

and so I do get my graph.

But if I have a DataFrame with a MultiIndex on the Columns, then I have a problem:

df = pd.DataFrame(np.array([[1,2,3,4,5],[3,4,5,6,7]]).T, columns=[['a','b'],['y','w']])

print(df)

which gives me:

   a  b
   y  w
0  1  3
1  2  4
2  3  5
3  4  6
4  5  7

so if I do now:

df.plot(x=['a','y'], y=['b','w'])
plt.show()

I get the following error:

File "pandas/_libs/index.pyx", line 117, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index.pyx", line 139, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 1265, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 1273, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'y'

Am I doing anything wrong?

Or is pandas not able to plot when using a MultiIndex?

Upvotes: 0

Views: 923

Answers (2)

Mike
Mike

Reputation: 53

I think this is a more straight forward way to do it:

df.plot(x=('a','y'), y=('b','w'))

Upvotes: 0

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210832

Try this:

df.set_index(('a','y')).plot()

Result:

enter image description here

Upvotes: 1

Related Questions