1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] matplotlib multiple Y-axis pandas plot

Discussão em 'Python' iniciado por Stack, Abril 5, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to do multiple Y axis plots.

    This is some made up data below, how could I put Temperature its own Y axis, Pressure on its own Y axis, and then have both Value1 and Value2 on the same Y axis. I am trying to go for the same look and feel of this SO post answer.

    I don't understand ax3 = ax.twinx() process; do I need to define an ax.twinx() for each separate Y axis plot I need?

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt



    rows,cols = 8760,4
    data = np.random.rand(rows,cols)
    tidx = pd.date_range('2019-01-01', periods=rows, freq='H')
    df = pd.DataFrame(data, columns=['Temperature','Value1','Pressure','Value2'], index=tidx)


    # using subplots() function
    fig, ax = plt.subplots(figsize=(25,8))
    plt.title('Multy Y Plot')

    ax2 = ax.twinx()
    ax3 = ax.twinx()
    ax4 = ax.twinx()

    plot1, = ax.plot(df.index, df.Temperature)
    plot2, = ax2.plot(df.index, df.Value1, color = 'r')
    plot3, = ax3.plot(df.index, df.Pressure, color = 'g')
    plot4, = ax4.plot(df.index, df.Value2, color = 'b')

    ax.set_xlabel('Date')
    ax.set_ylabel('Temperature')
    ax2.set_ylabel('Value1')
    ax3.set_ylabel('Pressure')
    ax4.set_ylabel('Value2')


    plt.legend([plot1,plot2,plot3,plot4],list(df.columns))

    # defining display layout
    plt.tight_layout()

    # show plot
    plt.show()


    This will output everything jumbled up on the same side without separate Y axis for Pressure, Value1, and Value2.

    [​IMG]

    Continue reading...

Compartilhe esta Página