Merging two figures with Pandas

Viewed 193

I have plotted the dataframe df as a stacked bar chart:

dft['Date'] = old['DATE'].dt.to_period('M')
df = dft.groupby(by=['Date', 'Size'])['Spend'].sum()  
stacked = df.unstack('Size').plot(kind='bar', stacked=True)

This stacked bar chart has bars sitting at every month.

I have another dataframe cir with quarterly data (every 3 months). I need this data as a bar covering all 3 months in the background of the main stacked bar chart. The following code plots the quarterly data on its own.

cir['date'] = ['3-15','4-15', '1-16', '2-16', '3-16', '4-16', '1-17', '2- 
17', '3-17', '4-17']
cir['value'] = [78.4, 13.5, 19.8, 19, 78.4, 123.2, 82.6, 86.4, 83.5, 12.2.4]
cir.plot.bar()

I would like to overlay these two plots (they have different y axis). I have tried using the subplots functionality but haven't really got anywhere.

1 Answers

This is more pseudo-code than actual code since you do not provide much information or the code you have written. Still, this can give you some hints on how to combine pandas.DataFrame.plot and matplotlib.pyplot.bar with different y axis.

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

width = 1
fig, ax1 = plt.subplots()
value_x = np.arange(cir['value'])
ax1.bar(x, cir['value'], width = 3*width)
ax2 = ax1.twinx()
df.unstack('Size').plot(kind='bar', stacked=True, ax=ax2, secondary_y=True, width=width)

plt.show()

Note that the trick is to use ax2 = ax1.twinx() and plot your series on a different axis.

About width, I am not sure if this will work since I do not know what is your x axis. But this is just to give you an idea on how to do it.

Related