Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Matplotlib subplot not plotting

I have the following code:

import pandas.util.testing as testing
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib as mpl

df = testing.makeTimeDataFrame(freq='MS')


with mpl.rc_context(rc={'font.family': 'serif', 'font.weight': 'bold', 'font.size': 12}):
    fig = plt.figure(figsize= (12, 6))

    
    fig.add_subplot(2, 2, (1,2))
    ax2 = ax.twinx()
    df['A'].plot(ax=ax, color = 'g')
    df['B'].plot(ax=ax2, color ='g')

    fig.add_subplot(223)
    df['C'].plot(color='r')
    
    fig.add_subplot(224)
    df['D'].plot()
    fig.tight_layout()
    plt.show()

Which produces the following plot.
enter image description here

I am trying to plot df['A'] and df['B'] on the same top plot. Could you please advise what I have overlooked?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

one little detail is missing. before calling twinx you need to assign ax to the first subplot. Then it’ll work.

ax = fig.add_subplot(2, 2, (1,2))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading