Plotly:当 scaleanchor = x 时,如何调整带注释的热图的轴标签?

Posted

技术标签:

【中文标题】Plotly:当 scaleanchor = x 时,如何调整带注释的热图的轴标签?【英文标题】:Plotly: How to adjust axis labels for annotated heatmaps when scaleanchor = x? 【发布时间】:2021-05-11 21:19:57 【问题描述】:

当您设置scaleanchor=x 和adjusting the aspect ratio 时,例如使用ff.annotated_heatmaps 制作一个完美的正方形热图,您最终会得到与x 轴本身有较大偏移的x 轴标签,如下所示:

如何解决这个问题?

代码:

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()

【问题讨论】:

【参考方案1】:

这个解决方案有点神秘,但请确保包含constrain='domain'

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

情节

完整代码

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()

【讨论】:

以上是关于Plotly:当 scaleanchor = x 时,如何调整带注释的热图的轴标签?的主要内容,如果未能解决你的问题,请参考以下文章

使用 Plotly.update() 更新轨迹的“x”和“y”值

如何在 plotly express 条形图中隐藏颜色条和图例?

Plotly:样式化辅助 x 轴

R plotly subplot 在图之间添加空间

格式化悬停数据标签 Plotly R

Plotly:如何使子图的 x 和 y 轴标题更大?