1

Let us say we have a dataframe as under:

index = pd.MultiIndex.from_tuples(zip(['A','A','A','A','B','B','B','B'],[2012,2013,2014,2015,2012,2013,2014,2015]))
df = pd.DataFrame({
    'col1':[10,20,10,30,50,20,60,80],
    'col2':[40,20,40,30,50,20,60,80],
    'col3':[10,20,80,30,80,20,80,10],
    },index=index)

I then added the names for these multi-index as 'Product' and 'Year' respectively.

Now I need to plot this data in such a way that for each 'Product' there is a different line for a specific column.

I tried this but it doesn't work.

df.plot(kind='line',x='Year')

I tried unstacking the dataframe using unstack(), however, as there are multiple columns, I will have to create as many new dataframes as there are columns for this to work.

Is there any other way?

1 Answer 1

1

You can unstack:

df['col'].unstack(level=0).plot()

Output:

enter image description here

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

2 Comments

I have updated the question about this unstack. Can you see if anything else works? I have too many columns instead of just one here.
I don't really get what you are asking. I'd say yes, unstacking for each column to get the plot is what I would do. You can also reset index and use seaborn's FacetGrid as well.

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.