0

I am trying to plot a stacked bar chart and a lineplot on the same plot but the second graph specified overwrites the first.

Below is the code I am using:

import seaborn as sns
import matplotlib.pyplot as plt
from datetime import datetime as dt

target_data = pd.read_csv('Target_levels.csv')
actual_data = pd.read_csv('Actual_Levels.csv')

actual_data['MTH'] = pd.to_datetime(actual_data['MTH'],format='%Y%m')
actual_data['PERIOD'] = actual_data['MTH'].dt.to_period("m")
actual_data.set_index('PERIOD',inplace=True)
actual_data.drop('MTH',axis=1,inplace=True)
    
target_data['MTH'] = pd.to_datetime(target_data['MTH'],format='%Y%m')
target_data['PERIOD'] = target_data['MTH'].dt.to_period("m")
target_data.set_index('PERIOD',inplace=True)
target_data.drop('MTH',axis=1,inplace=True)

fig, ax1 = plt.subplots(figsize = (10, 10))
ax2 = plt.twinx(ax = ax1)
actual_data.plot(kind = 'bar', stacked = True, ax = ax1)
target_data.plot(ax = ax1, alpha = 0.5)
plt.show()

The format of each data input is as below:

MTH weight_one weight_two weight_three weight_four
201707 0.2 0.5 0.25 0.05
201708 0.21 0.5 0.25 0.04
201709 0.2 0.48 0.27 0.05
201710 0.2 0.5 0.25 0.05

I am able to chart both sets of data independently but can not get them to appear in the same plot without overwriting each other.

Any help you may be offer with this problem would be greatly appreciated.

Thanks you in advance!

JP1999JP
  • 41
  • 1
  • 7
  • Maybe you want to use `ax2` for the second plot: `target_data.plot(ax=ax2, alpha = 0.5)`? – JohanC Sep 20 '21 at 10:32
  • 1
    Both `actual_data` and `target_data` are plotted against the index. In order to plot them together and line-up, the index should be a ranged index beginning at 0, and then set the axis tick labels after. See this [answer](https://stackoverflow.com/a/69106955/7758804) – Trenton McKinney Sep 20 '21 at 17:44
  • 1
    The index issue seemed to be the problem, all works well now. Many thanks for your help with this problem! – JP1999JP Sep 21 '21 at 09:58

0 Answers0