How To Make Stacked Line Chart With Different Y-axis In Matplotlib?
I am wondering how should I make stacked line chart which is gonna take different columns in matplotlib. The point is when we are doing aggregation, I need to do data aggregation o
Solution 1:
Pandas groupby feature is very versatile, and you can reduce the lines of code considerably to achieve the final dataframe for plotting.
plotdf = df_re.groupby([ 'retail_item',df_re['date'].dt.year,df_re['date'].dt.week]).agg({'number_of_ads':'sum','price_gap':'mean'}).unstack().T
Once you have the aggregation done the right way, use a for loop to show each of the measures needed in a different plot. Plot a shaded range by using pandas describe feature to compute the min and max on the fly:
f,axs = plt.subplots(2,1,figsize=(20,14))
axs=axs.ravel()
for i,x in enumerate(['number_of_ads','price_gap']):
plotdf.loc[x].plot(rot=90,grid=True,ax=axs[i])
plotdf.loc[x].T.describe().T[['min','max']].plot(kind='area',color=['w','grey'],alpha=0.3,ax=axs[i],title= x)
Edit with updated code:
plotdf = df_re.groupby(['retail_item',df_re['date'].dt.year,df_re['date'].dt.week]).agg({'number_of_ads':'sum','weighted_avg':'mean'}).unstack().T
f,axs = plt.subplots(3,2,figsize=(20,14))
axs=axs.ravel()
i=0for col in plotdf.columns.get_level_values(0).unique():
for x in ['number_of_ads','weighted_avg']:
plotdf.loc[x,col].plot(rot=90,grid=True,ax=axs[i]);
plotdf.loc[x,col].T.describe().T[['min','max']].plot(kind='area',color=['w','grey'],alpha=0.3,ax=axs[i],title= col+', '+x)
i+=1
Post a Comment for "How To Make Stacked Line Chart With Different Y-axis In Matplotlib?"