Plotly graphs two yaxis

54 Views Asked by At

does anyone knows why this happens? Seens that my frist and my last point are connected …

Plot img

enter image description here

the code:

df = pd.read_csv(‘data.csv’, index_col=0, parse_dates=True)

def plot_var_prev(dff):

    fig = make_subplots(specs=[[{"secondary_y": True}]])
    fig.add_trace(
        go.Scatter(x=dff.index, 
                y=dff['mag_vento'].values,
                name="Magnitude"),
                secondary_y=False,
    )

    fig.add_trace(
        go.Scatter(x=dff.index, 
                y=dff['direcao_vento'].values, 
                name="Direção"),
                secondary_y=True,
    )

    fig.update_xaxes(title_text="<b>Data</b>")
    fig.update_layout(hovermode="x", hoverlabel=dict(font_size=16, font_family="Poppins"))
    fig.update_layout(plot_bgcolor='rgba(0, 0, 0, 0)', paper_bgcolor='rgba(0, 0, 0, 0)',)
    fig.update_layout(
            legend=dict(orientation="v"),
            yaxis=dict(
                title=dict(text='<b>Magnitude do vento [m/s]</b>'),
                side="left",
                type='linear'
            ),
            yaxis2=dict(
                title=dict(text="<b>Direção do vento [°]</b>"),
                side="right",
                type='linear',
                overlaying="y",
                tickmode="sync",
                rangemode='tozero'
            ),
        )
    
    return fig

the data:

https://raw.githubusercontent.com/josepaulo1233/plotly-wind-graphs/main/data.csv

I trying not use some parameters but nothing is happen

2

There are 2 best solutions below

1
GebaiPerson On

You can simply achieve that with matplotlib.axes.Axes.twinx. Here's a simple example of plotting a sine wave and a consine wave sharing the same x-axis but having different y-axis scales.

import numpy as np
from matplotlib import pyplot as plt

def main():
    x_axis = np.linspace(0, 2 * np.pi, 50)
    sine = np.sin(x_axis)
    cosine = np.cos(x_axis)

    fig, ax = plt.subplots() 
    # twinx is a method of Axes class
    # use the plt.subplots method to create an axe object so you can call the twinx method on it

    ax.plot(x_axis, sine)
    ax.set_ylabel("Sine wave")
    ax_twin = ax.twinx()

    ax_twin.plot(x_axis, cosine * 420)
    ax_twin.set_ylabel("Cosine wave")
    plt.show()

if __name__ == "__main__":
    main()

And here's the result: Sine wave in blue and cosine wave in red

0
Derek O On

I think your index might not be completely sorted so some points are connected out of order in time. You can try sorting the index of dff before creating traces inside your plot_var_prev function:

import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots

df = pd.read_csv('https://raw.githubusercontent.com/josepaulo1233/plotly-wind-graphs/main/data.csv', index_col=0, parse_dates=True)

def plot_var_prev(dff):

    fig = make_subplots(specs=[[{"secondary_y": True}]])
    dff = dff.sort_index() ## ⭠ sort by index
    fig.add_trace(
        go.Scatter(x=dff.index, 
                y=dff['mag_vento'].values,
                name="Magnitude"),
                secondary_y=False,
    )

    fig.add_trace(
        go.Scatter(x=dff.index, 
                y=dff['direcao_vento'].values, 
                name="Direção"),
                secondary_y=True,
    )

    fig.update_xaxes(title_text="<b>Data</b>")
    fig.update_layout(hovermode="x", hoverlabel=dict(font_size=16, font_family="Poppins"))
    fig.update_layout(plot_bgcolor='rgba(0, 0, 0, 0)', paper_bgcolor='rgba(0, 0, 0, 0)',)
    fig.update_layout(
            legend=dict(orientation="v"),
            yaxis=dict(
                title=dict(text='<b>Magnitude do vento [m/s]</b>'),
                side="left",
                type='linear'
            ),
            yaxis2=dict(
                title=dict(text="<b>Direção do vento [°]</b>"),
                side="right",
                type='linear',
                overlaying="y",
                tickmode="sync",
                rangemode='tozero'
            ),
        )
    
    return fig

fig = plot_var_prev(df)
fig.show()

enter image description here