chessosapiens
chessosapiens

Reputation: 3409

Plot wide data using pandas and matplotlib

I have the following pandas dataframe:

         var    sales
month       
2017-01-01  1   356558.02
2017-01-01  2   295062.54
2017-01-01  3   236702.53
2017-02-01  1   305813.24
2017-02-01  2   348966.32
2017-02-01  3   364121.50
2017-03-01  1   292793.76
2017-03-01  2   345290.65
2017-03-01  3   361361.49
2017-04-01  1   265695.47
2017-04-01  2   351965.57
2017-04-01  3   520796.56

How can I plot month in the x axis and sales in the y axis and three different lines: each one corresponding to a value in the var column? I need to represent how sales for each var changes over time.

Upvotes: 0

Views: 915

Answers (1)

Arya McCarthy
Arya McCarthy

Reputation: 8829

Start by pivoting your data so it's in the form that you want. Then plot.

df = df.pivot(index='month', columns='var', values='sales')
df.plot()

The pivot gets you this:

month        1           2           3
2017-01-01   356558.02   295062.54   236702.53
2017-02-01   305813.24   348966.32   364121.50
2017-03-01   292793.76   345290.65   123456.78

From there, the intent should be much clearer.

Upvotes: 2

Related Questions