Search code examples
plotly-python

plotly imagesc repeat yaxis labels


I have a wide matrix that I render using plotly express. Let's say:

import plotly.express as px
data=[[1, 25, 30, 50, 1], [20, 1, 60, 80, 30], [30, 60, 1, 5, 20]]
fig = px.imshow(data,
                labels=dict(x="Day of Week", y="Time of Day", color="Productivity"),
                x=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
                y=['Morning', 'Afternoon', 'Evening']
               )
fig.update_xaxes(side="top")

fig.layout.height = 500
fig.layout.width = 500

fig.show()

For enhancing readability, I would like to repeat (or add an identical) yaxis on the right side of the matrix.

I tried to follow this

fig.update_layout(xaxis=dict(domain=[0.3, 0.7]),
    # create 1st y axis
    yaxis=dict(
    title="yaxis1 title",),
    # create 2nd y axis
    yaxis2=dict(title="yaxis2 title", anchor="x", overlaying="y",
                side="right")
    )

but I cannot make it work with imshow as it does not accept a yaxis argument.

Any workarounds?


Solution

  • Found an answer through the plotly forum:

    import plotly.graph_objects as go
    from plotly.subplots import make_subplots
    
    # Create figure with secondary y-axis
    fig = make_subplots(specs=[[{"secondary_y": True}]])
    
    data=[[1, 25, 30, 50, 1], [20, 1, 60, 80, 30], [30, 60, 1, 5, 20]]
    
    fig.add_trace(go.Heatmap(
                    z=data,
                    x=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
                    y=['Morning', 'Afternoon', 'Evening']
    ),secondary_y=False)
    fig.add_trace(go.Heatmap(
                    z=data,
                    x=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
                    y=['Morning', 'Afternoon', 'Evening']
    ),secondary_y=True)
    
    fig.update_xaxes(side="top")
    fig.update_layout(xaxis_title="Day of Week", yaxis_title="Time of Day")
    
    fig.show()
    

    Note that adding the trace twice may be suboptimal, but it works.