Home > Mobile >  Matplotlib subplot not plotting
Matplotlib subplot not plotting

Time:08-22

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?

CodePudding user response:

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))
  • Related