首页 > 解决方案 > Plotly:如何设置热图纵横比?

问题描述

我有一个单通道图像,其中每个整数像素值映射到一个字符串。例如 5 -> '人'。我正在尝试创建一个交互式图像,将鼠标悬停在一个像素上将显示它的相应字符串。

我认为使用 plotly 热图可能是做到这一点的方法。我遇到的问题是:

有谁可以帮我离开这里吗?这是我所拥有的:

import numpy as np
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
import plotly.figure_factory as ff

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)

fig = ff.create_annotated_heatmap(z, annotation_text=z_text, text=class_mat, hoverinfo='text', colorscale='Viridis', )
fig.layout.title = 'Semantic Segmentation'

iplot(fig, filename='annotated_heatmap_text')

这是它目前的样子:

在此处输入图像描述

此外,如果情节热图不是解决此问题的最佳方式,我很乐意听到任何替代方案!

注意:我目前正在 jupyterlab 中显示。

标签: pythonplotlyheatmapsemantic-segmentation

解决方案


我不确定我是否在这里得到了正确的每个细节,但下面代码片段中的代码将在 Jupyter Notebook 中生成以下图。处理纵横比的行是:

fig['layout']['yaxis']['scaleanchor']='x'

您还可以使用:

fig.update_layout(yaxis = dict(scaleanchor = 'x'))

情节1:

在此处输入图像描述

情节2:

只要确保包括:

fig.update_layout(plot_bgcolor='rgba(0,0,0,0)')

否则你会得到这个:

在此处输入图像描述

代码 1 - 我对您的示例的编辑:

fig.data[0]['hoverinfo'] = 'all'
fig['layout']['yaxis']['scaleanchor']='x'
fig['layout']['xaxis']['gridcolor'] = 'rgba(0, 0, 0, 0)'
fig['layout']['yaxis']['gridcolor'] = 'rgba(0, 0, 0, 0)'
fig['layout']['yaxis']['color'] = 'rgba(0, 0, 0, 0)'

代码 2 - 轻松复制和粘贴的全部内容:

import numpy as np
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
import plotly.figure_factory as ff

#%qtconsole

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)

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'

# My suggestions:
fig.data[0]['hoverinfo'] = 'all'
fig['layout']['yaxis']['scaleanchor']='x'

fig['layout']['xaxis']['gridcolor'] = 'rgba(0, 0, 0, 0)'
fig['layout']['yaxis']['gridcolor'] = 'rgba(0, 0, 0, 0)'
fig['layout']['yaxis']['color'] = 'rgba(0, 0, 0, 0)'

fig.update_layout(plot_bgcolor='rgba(0,0,0,0)')

fig.show()

速度:

即使是这个小数字也需要一些时间来绘制,但到目前为止,我对如何加快速度没有任何建议。


推荐阅读