0

I want to create a combined bar chart and line graph all in the same plot with the same x-axis. They all exist in the same dataframe as well. The result only returns bar charts as expected but I don't know how to overlap the line graph with the bar chart data. The relevant data for the bar chart is the 'No Churn', and 'Grand Total'. The relevant line chart data is the ['0-3', '4-11', '12+]. Here is an example dataframe with the current output and also the expected output shown as two graphs that I want to combine together.

df_rand = pd.DataFrame(np.random.randint(0,100,size=(10, 5)), columns=['No Churn', 'Grand Total', '0-3', '4-11', '12+'])
df_rand['Snapshot_Month'] = ['2020-01', '2020-02', '2020-03', '2020-04', '2020-05', '2020-06', '2020-07', '2020-08', '2020-09', '2020-10']

plt.style.use('ggplot')
ax = df_rand.plot(x='Snapshot_Month', kind='bar', title ="Cohort",figsize=(20,10),legend=True, fontsize=12)
ax.set_xlabel('Snapshot_Month')
ax.set_ylabel('No Churn')
ax.set_ylabel('Amount')

enter image description hereExpected output

plt.style.use('ggplot')
ax = df_rand[['Snapshot_Month', 'No Churn', 'Grand Total']].plot(x='Snapshot_Month', kind='bar', title ="Cohort",figsize=(20,5),legend=True, fontsize=12)
ax.set_xlabel('Snapshot_Month')
ax.set_ylabel('Amount')

###combined with###
plt.style.use('ggplot')
ax = df_rand[['Snapshot_Month', '0-3', '4-11', '12+']].plot(x='Snapshot_Month', kind='line', title ="Cohort",figsize=(20,5),legend=True, fontsize=12)
ax.set_xlabel('Snapshot_Month')
ax.set_ylabel('Amount')

enter image description here enter image description here

Deke Marquardt
  • 111
  • 1
  • 9

1 Answers1

1

Using the ax parameter you can pass a plot to another

plt.style.use('ggplot')

# adding plot configurations to the first plot
ax1 = df_rand[['Snapshot_Month', 'No Churn', 'Grand Total']].plot(x='Snapshot_Month', kind='bar', figsize=(20,5), legend=True, fontsize=12)

# adding parameter ax with value ax1 
ax2 = df_rand[['Snapshot_Month', '0-3', '4-11', '12+']].plot(x='Snapshot_Month', kind='line', legend=True, ax=ax1)

# assigning labels and titles to the last plot
ax2.set_title('Cohort')
ax2.set_xlabel('Snapshot_Month')
ax2.set_ylabel('Amount')

plt.show()

enter image description here

Also, I would suggest adding plot configurations only to the first plot, and adding title and labels on the last plot would be a good practice to avoid inconsistency.

skt7
  • 1,197
  • 8
  • 21