1

When you set scaleanchor=x when adjusting the aspect ratio, for example to make a perfectly square heatmap using ff.annotated_heatmaps, you'll end up with x-axis labels with a large offset from the x-axis itself like this:

enter image description here

How can you fix that?

Code:

import numpy as np
import plotly.graph_objs as go
import plotly.figure_factory as ff

# data
z = np.random.randint(0,6, size=(10, 10))
z_text = np.full(z.shape, '', dtype=str)
d = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e', 5:'f'}
class_mat = np.vectorize(d.get)(z)

# plotly figure factory annotated heatmap
fig = ff.create_annotated_heatmap(z, annotation_text=z_text,
                                  text=class_mat, hoverinfo='text', colorscale='Viridis',
                                  x = list('ABCDEFGHIJ'),
                                  y = list('ABCDEFGHIJ')
                                 )
fig.layout.title = 'Semantic Segmentation'
fig.data[0]['hoverinfo'] = 'all'

# adjustment 1: scaleanchor => squared figure
fig['layout']['yaxis']['scaleanchor']='x'

# adjustment 2: remove redunant background background
fig.update_layout(plot_bgcolor='rgba(0,0,0,0)')

fig.show()
vestland
  • 55,229
  • 37
  • 187
  • 305

1 Answers1

1

This solution is a bit cryptic, but just make sure to include constrain='domain':

fig.update_layout(xaxis=dict(scaleanchor='y',constrain='domain'))

Plot

enter image description here

Complete code

import numpy as np
import plotly.graph_objs as go
import plotly.figure_factory as ff

# data
z = np.random.randint(0,6, size=(10, 10))
z_text = np.full(z.shape, '', dtype=str)
d = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e', 5:'f'}
class_mat = np.vectorize(d.get)(z)

# plotly figure factory annotated heatmap
fig = ff.create_annotated_heatmap(z, annotation_text=z_text,
                                  text=class_mat, hoverinfo='text', colorscale='Viridis',
                                  x = list('ABCDEFGHIJ'),
                                  y = list('ABCDEFGHIJ')
                                 )
fig.layout.title = 'Semantic Segmentation'
fig.data[0]['hoverinfo'] = 'all'

# adjustment 1: scaleanchor => squared figure
fig['layout']['yaxis']['scaleanchor']='x'

# adjustment 2: remove redunant background background
fig.update_layout(plot_bgcolor='rgba(0,0,0,0)')

# adjustment 3: x-axis label offsets
fig.update_layout(xaxis=dict(scaleanchor='y',constrain='domain'))

fig.show()
vestland
  • 55,229
  • 37
  • 187
  • 305