Search code examples
python-3.xplotlyplotly-python

plotly python change y-axis values ​to your own


A graph of random values ​​is plotted. It is necessary to change the values ​​of the Y axis to others.

xg = np.random.rand(100, 1200)
fig = px.imshow(xg, aspect="auto",color_continuous_scale='ice')
fig.show()

values ​​to be changed

y1=np.arange(100)*0.5
y2=np.arange(100)*5

Thanks!


Solution

    • 100 ticks on the yaxis is too many! Have gone with 10
    • simple case of defining where you want ticks in the range of values (100) and text you want to display again domain value https://plotly.com/python/tick-formatting/#tickmode--array
    • the multiplications are equivalent to your requirements, just generating arrays of appropriate length (ten ticks)
    import numpy as np
    import plotly.express as px
    
    xg = np.random.rand(100, 1200)
    fig = px.imshow(xg, aspect="auto",color_continuous_scale='ice')
    
    # y1
    fig.update_layout(yaxis={"tickmode":"array","tickvals":np.arange(10)*10, "ticktext":np.arange(10)*5}).show()
    # y2
    fig.update_layout(yaxis={"tickmode":"array","tickvals":np.arange(10)*10, "ticktext":np.arange(10)*50}).show()
    
    
    

    supplementary - show both y-axis

    • as per comment you can use documented approach https://plotly.com/python/multiple-axes/#multiple-axes
    • you do require a trace per axis hence creation of two traces and modification of second trace to use y2
    • setting second trace to "visible":False does not work. So there are two identical traces on top of each other
    import numpy as np
    import plotly.express as px
    
    xg = np.random.rand(100, 1200)
    fig = px.imshow(xg, aspect="auto", color_continuous_scale="ice").add_traces(
        px.imshow(xg, aspect="auto", color_continuous_scale="ice")
        .update_traces(yaxis="y2")
        .data
    )
    
    fig.update_layout(
        xaxis={"domain": [0.05, 1]},
        yaxis={
            "tickmode": "array",
            "tickvals": np.arange(10) * 10,
            "ticktext": np.arange(10) * 50,
        },
        yaxis2={
            "tickmode": "array",
            "tickvals": np.arange(10) * 10,
            "ticktext": np.arange(10) * 5,
            "anchor": "free",
            "position": 0,
            "autorange": "reversed",
        },
    ).show()