0

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?

4
  • You can. You just need to set the index before plotting. Try df.set_index(('a', 'y')).plot(). Commented Dec 13, 2017 at 13:28
  • Thanks, this work, but is just a workaround. I expect the function plot(x=['a','y'], y=['b','w']) to work both with single and with multiple column index. Commented Dec 13, 2017 at 13:41
  • Well, sorry, but it won't. Commented Dec 13, 2017 at 13:42
  • No, I see it won't, but I think then pandas should work on it for code coherency. Commented Dec 13, 2017 at 13:43

2 Answers 2

1

Try this:

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

Result:

enter image description here

Sign up to request clarification or add additional context in comments.

5 Comments

Aha, didn't see your answer when I posted my comment.
@cᴏʟᴅsᴘᴇᴇᴅ, thank you! Congratulations! You are [legendary] now! ;-)
Thank you so much! Couldn't have done it without you guys :-)
@cᴏʟᴅsᴘᴇᴇᴅ Congratulations !! lengendary achieved
@Wen Thanks, couldn't have done it without you guys' help!
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.