Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Plot 2 lines based on the value not column

I have a data set:

ReviewDate_year,ReviewDate_month,Sales
 2010,11,1
 2011,02,2
 2011,11,1
 2011,12,6
 2012,01,11
 2012,02,8
 2012,03,3
 2012,04,1
 2012,05,8
 2012,06,3
 2012,07,1
 2012,08,2
 2012,09,1
 2012,11,1
 2012,12,8
 2013,01,2
 2013,02,2
 2013,03,4
 2013,04,4
 2013,05,7
 2013,06,5
 2013,07,6
 2013,08,4
 2013,09,4
 2013,10,5
 2013,11,3
 2013,12,5
 2014,01,9
 2014,02,4
 2014,03,8
 2014,04,7
 2014,05,3
 2014,06,7
 2014,07,1

How do I plot Sales by month and different year in different line

I can certainly do it by year

df_2013 = df_monthlycount[df_monthlycount['ReviewDate_year'] == 2013]
df_2014 = df_monthlycount[df_monthlycount['ReviewDate_year'] == 2014]

df_2013.plot(x='ReviewDate_month',y='ProductId')

plt.show()

but how can I make lines of different year in a single chart?

like image 754
Jasmine Avatar asked Jul 24 '26 18:07

Jasmine


1 Answers

You can use groupby plot. Instead of creating one ax for each group, you can specify an ax and have everything plotted on that ax:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm

ax = plt.subplot(111)
df[df.ReviewDate_year.isin([2012,2013])].groupby('ReviewDate_year').plot(y='Sales', x='ReviewDate_month', kind='line', ax=ax)
L = plt.legend()
_ = [plt.setp(item, 'text', T) for item, T in zip(L.texts, ['2012','2013'])]
_ = ax.set_xticks(df.ReviewDate_month.unique())

enter image description here

like image 84
CT Zhu Avatar answered Jul 27 '26 06:07

CT Zhu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!