Plotting Line Plot On Top Of Bar Plot In Python / Matplotlib From Dataframe
I am trying to plot a line plot on top of a stacked bar plot in matplotlib, but cannot get them both to show up. I have the combined dataframe already set up by pulling various inf
Solution 1:
Figured it out! By leaving the dates as a column (i.e. not setting them as the index), I can plot both the line plot and bar plot. I can then go back and adjust labels accordingly.
@ScottBoston your x-axis tipped me off. Thanks for looking into this.
date1 = pd.datetime(2018, 4, 10)
data = {'LightlyActive': [314, 253, 282, 292],
'FairlyActive': [34, 22, 26, 35],
'VeryActive': [123, 102, 85, 29],
'efficiency': [93.0, 96.0, 93.0, 96.0],
'wake': [55.0, 44.0, 47.0, 43.0],
'light': [225.0, 260.0, 230.0, 205.0],
'deep': [72.0, 50.0, 60.0, 81.0],
'rem': [99.0, 72.0, 97.0, 85.0],
'date': [date1 + pd.Timedelta(days = i) for i in range(4)]}
temp_df = pd.DataFrame(data)
fig, ax1 = plt.subplots(figsize = (10, 10))
ax2 = plt.twinx(ax = ax1)
temp_df[['LightlyActive', 'FairlyActive', 'VeryActive']].\
plot(kind = 'bar', stacked = True, ax = ax1)
temp_df[['wake', 'light', 'deep', 'rem']].plot(ax = ax1, alpha = 0.5)
temp_df['efficiency'].plot(ax = ax2)
ax1.set_xticklabels(labels = temp_df['date'])
plt.show()
Solution 2:
What about using alpha
?
fig, ax1 = plt.subplots(figsize = (10, 10))
temp_df[['LightlyActive', 'FairlyActive', 'VeryActive']].plot(kind = 'bar', stacked = True, ax = ax1, alpha=.3)
ax2 = plt.twinx(ax = ax1)
temp_df[['wake', 'light', 'deep', 'rem']].plot(ax = ax1, zorder=10)
temp_df['efficiency'].plot(ax = ax2)
plt.show()
Output:
Post a Comment for "Plotting Line Plot On Top Of Bar Plot In Python / Matplotlib From Dataframe"