Colorbar location for heatmap when aspect ratio locked

Is it possible to keep my colorbar aligned relative to the right edge of my heatmap when the aspect ratio is locked with xaxis.scaleanchor = 'y'? The fig.layout.coloraxis.colorbar.x seems to describe the horizontal position including the whitespace to the left and right of the square heatmap (whitespace depends on heatmap pixel width and jupyter notebook window width), and I don’t think fig.layout.coloraxis.colorbar.xpad offers a solution. Thanks!

Hi @tks, there is no straightforward way to do what you want because with the scaleanchor set, the size of the plot is not known beforehand (in plotly the positioning of most elements is explicit, except for the margins, eg with automargin). You can either control explicitely the position of the colorbar as you suggested:

import plotly.graph_objects as go
import numpy as np
z = np.random.random((10, 5))
fig = go.Figure(go.Heatmap(z=z, coloraxis='coloraxis'))
fig.update_layout(xaxis=dict(scaleanchor='y', constrain='domain'),
                  coloraxis_colorbar_x=0.65
                 )
fig.show()

but this requires trial and error, so a better solution, if the dimensions of your heatmap can vary, is to create a figure which has the right aspect ratio to fit tightly the heatmap + some space for the colorbar, like

import plotly.graph_objects as go
import numpy as np
l_0, l_1 = 10, 5
z = np.random.random((l_0, l_1))
width = 500
fig = go.Figure(go.Heatmap(z=z, coloraxis='coloraxis'))
fig.update_layout(xaxis=dict(scaleanchor='y', constrain='domain'),
                  width=width + 50, # add 50 for colorbar 
                  height=int(width * l_0 / l_1) 
                 )
fig.show()

Hope this helps!

Thanks @Emmanuelle! The explicit width declaration was the way to go!

1 Like