Search code examples
pythonplotlyinteractive

Is there an easy way to add a secondary y-axis to a Plotly plot without the need of providing a second array?


I want to have two y-axes for the same time series, an axis with the absolute number as values, and an axis with the percentages as values. Draft schematics of the desired outcome


Solution

  • I don't see a way of doing it without 2 traces. It does mean each trace can be switched on / off in legend so that hover gives interactivity.

    import numpy as np
    import pandas as pd
    import plotly.graph_objects as go
    
    x = pd.date_range("14-feb-2022", freq="1H", periods=400)
    y = np.sort(np.random.pareto(2, 400))[::-1]
    
    go.Figure(
        [
            go.Scatter(x=x, y=y, name="abs"),
            go.Scatter(
                x=x,
                y=y / y.max(),
                name="% max",
                yaxis="y2",
            ),
        ],
        layout={
            "yaxis2": {
                "side": "right",
                "tickformat": ",.0%",
            },
            "yaxis": {"overlaying": "y2"},
            "legend": {"orientation": "h", "xanchor": "center", "x": 0.5},
        },
    )
    

    enter image description here