Adding a secondary y axis on heatmap in plotly express python

Question:

i would like to add a second y axis to my plotly express heatmap, but unfortunately i can’t do it and just can’t find any infos.

already tried stuff like that:
Plotly: How to plot on secondary y-Axis with plotly express

short code to explain it:

 z = [[0.5,0.5],[1,1],[0.6,0.3],[1,0.4]]
 x = ["p1","p2"]
 y = ["A","B","C","D"]
 fig = px.imshow(z, x=x, y=y, zmin=0, zmax=1)
 fig.show()

output:

plot without second y axis

now add second y axis:

y2 = [1,2,3,4]

what i want to achieve:

plot with second y axis as i would like it to be

Name: plotly
Version: 5.11.0

Python 3.9.6

thank you so much!


Update

with the help of @r-beginners i was able to add the 2 y axis. unfortunately i have values in the second y axis that are not unique and therefore always summarized.

Example with:

y2 = [1,2,2,4]

x,y and z stay the same.

result with new y2

I can of course make the values in y2 unique to get the plot i need, but isn’t there a better way?

Unique y2:

y2 = ["1_0","2_1","2_2","4_3"]

Leads to the desired result, but not very nice:

with updated y2

Thanks again for your help! 🙂

Asked By: Jean

||

Answers:

To create a subplot, use the graph object to activate the second axis. That will create two heat maps. The basics are now complete, I added the y-axis in reverse order and the graph in the same vertical and horizontal size to keep the aspect ratio the same.

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

fig = make_subplots(rows=1,cols=1, specs=[[{'secondary_y': True}]])

fig.add_trace(go.Heatmap(x=x, y=y, z=z), secondary_y=False)
fig.add_trace(go.Heatmap(x=x, y=y2, z=z), secondary_y=True)
                    
fig.update_yaxes(autorange='reversed')
fig.update_layout(height=450, width=450)
fig.show()

enter image description here

Answered By: r-beginners