Combine two graphs into one figure using two y-axis

I divided my dataFrame into two subs as below and plot one stacked bar and one line graphs. Please help me how to combine them into one figure using two y-axis with the same x-axis?

Thank you,

import pandas as pd
import matplotlib.pyplot as plt
df1 = pd.DataFrame([[‘16-Jun-21’, 0, 41.86, 2.33, 8.14, 41.86, 5.81], [‘29-Jul-21’, 0, 65.08, 0, 6.07, 24.51, 4.34], [‘11-Aug-21’, 0, 49.66, 0, 5.52, 37.93, 6.9], [‘15-Sep-21’, 0, 51.12, 0, 3.19, 31.63, 14.06],
[‘6-Oct-21’, 0, 65.79, 0, 6.73, 20.56, 6.92], [‘3-Nov-21’, 0, 57.03, 0, 5.54, 34.06, 3.37],
[‘1-Dec-21’, 0, 35.49, 17.74, 5.91, 32.53, 8.32], [‘30-Dec-21’, 0, 71.46, 0, 2.98, 21.84, 3.72], [‘27-Jan-22’, 0.21, 51.45, 0, 0.83, 42.74, 4.56], [‘23-Feb-22’, 0, 40, 0, 4, 46, 10],
[‘23-Mar-22’, 0, 33.33, 15.52, 4.02, 38.51, 8.62], [‘20-Apr-22’, 0, 3.19, 0, 1.59, 94.02, 1.2],
[‘18-May-22’, 0, 7.08, 17.7, 3.54, 64.16, 7.52], [‘15-Jun-22’, 0, 0, 56.46, 0, 33.88, 9.66],
[‘20-Jul-22’, 0, 0, 15.23, 2.03, 78.17, 4.57]], columns=[‘Date’, ‘Cylindrospermopsis raciborskii’, ‘Merismopedia sp.’, ‘Aphanocapsa sp.’, ‘Chroococcus sp.’, ‘Gloeocapsa sp.’, ‘Planktolyngbya sp.’])

df2=pd.DataFrame([[‘16-Jun-21’, 330], [‘29-Jul-21’, 961], [‘11-Aug-21’, 834], [‘15-Sep-21’, 612], [‘6-Oct-21’, 564], [‘3-Nov-21’, 537], [‘1-Dec-21’, 595], [‘30-Dec-21’, 876], [‘27-Jan-22’, 518], [‘23-Feb-22’, 225],
[‘23-Mar-22’, 710], [‘20-Apr-22’, 259], [‘18-May-22’, 476], [‘15-Jun-22’, 716], [‘20-Jul-22’, 219]], columns=[‘Date’, ‘Total Cyanobacteria’])

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot = df1.plot(x=‘Date’, kind=‘bar’, stacked=True)
ax2.plot = df2.plot(x=‘Date’, color=‘red’)
plt.plot()
plt.show()
image

Those last 2 lines seem to set .plot on each axis. Not what you want;
it has no real effect. Instead, the calls to .plot() make distinct
plots.

What you want is to tell the .plot() call which axes to use:

 df1.plot(ax=ax1, x='Date', kind='bar', stacked=True)
 df2.plot(ax=ax2, x='Date', color='red')

Cheers,
Cameron Simpson cs@cskk.id.au

···

On 22Apr2023 02:40, Nguyenthanh Kien via Matplotlib nobody@discourse.matplotlib.org wrote:

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot = df1.plot(x=‘Date’, kind=‘bar’, stacked=True)
ax2.plot = df2.plot(x=‘Date’, color=‘red’)

Followup:

  • the df1.plot(ax=ax1,.....) call is complete - you don’t need or want the ax1.plot= tuff
  • something’s turned yourcode quotes into “smart quotes” above; I had to hand replace them with ASCII apostrophe marks

Usually if you paste code into this forum you should enclose it in “code fences”, eg:

```
your code
goes here
```

There’s a </> icon in the compose toolbar to made such a section for you. This also preserves formatting and punctuation.

Many thanks Cameron. They are now in one figure. Can you help me how to combine both legends in one and place it on the right, outside the border please?

This legend example might help, but note that the “outside” functionality is only available since Matplotlib v3.7.
https://matplotlib.org/stable/tutorials/intermediate/legend_guide.html#figure-legends

Hi rcomer,

I have tried but it does not work with my plots.

Here is my coding, but I CANNOT combine the legend of line with the legend of stacked bar. Can you help me to resolve my issue?
import os
import pandas as pd

from pandas import DataFrame
from pandas import read_csv
import matplotlib.pyplot as plt

#import the spreadsheet

df = pd.read_csv(‘DRR_DASWDR01C_Cyanobacteria_cells_2021-22.csv’,header=[0], index_col=0)

df1 = pd.DataFrame(df, columns=[‘Date’, ‘Cylindrospermopsis raciborskii’,
‘Merismopedia sp.’, ‘Aphanocapsa sp.’,
‘Chroococcus sp.’, ‘Phormidium sp.’, ‘Gloeocapsa sp.’, ‘Planktolyngbya sp.’])
print(df1)

Cyacells=df1.loc[:,(‘Cylindrospermopsis raciborskii’,
‘Merismopedia sp.’, ‘Aphanocapsa sp.’,
‘Chroococcus sp.’, ‘Phormidium sp.’, ‘Gloeocapsa sp.’, ‘Planktolyngbya sp.’)]

df2 = pd.DataFrame(df, columns=[‘Date’, ‘Total Cyanobacteria’])
print(df2)

TotalCya=df2.loc[:,(‘Total Cyanobacteria’)]

fig, ax1 = plt.subplots(figsize = (15, 11))
plt.suptitle(‘Total Cyanobacteria’)

ax2 = ax1.twinx()

Cyacells.plot(ax = ax1, kind=‘bar’, stacked=True, colormap=‘tab20’)

TotalCya.plot(ax = ax2, color=‘black’, linewidth=2.5)

ax1.legend(loc= ‘upper left’, bbox_to_anchor=(1.05, 1), fontsize= 14)

ax1.set_ylabel(‘%’, color=‘black’, fontsize=14)

ax2.set_ylabel(‘Total Cyanobacteria’, color=‘black’, fontsize=14)

plt.show()

I would try fig.legend instead of ax1.legend.

Hi rcomer,

I have tried fig.legend instead of ax1.legend but the result is the same, for only one legend of stacked bar not includes the line graph.