python Plotly:如何在带注解的热图中圆形显示文本,但在悬停时保持完整格式?

hs1ihplo  于 2023-06-20  发布在  Python
关注(0)|答案(4)|浏览(118)

我正在绘制泰坦尼克号数据集的相关矩阵。

df_corr = df.corr()

最初,矩阵看起来像这样:

fig = ff.create_annotated_heatmap(
            z=df_corr.to_numpy(),
            x=df_corr.columns.tolist(),
            y=df_corr.index.tolist(),
            zmax=1, zmin=-1,
            showscale=True,
            hoverongaps=True
            )
# add title
fig.update_layout(title_text='<i><b>Correlation not round</b></i>')

我想对浮点数进行四舍五入,这样它们在.点之后显示的数字就少了。
当前的解决方法实际上是在输入之前绕过pandas Dataframe 。

df_corr_round = df_corr.round(3)
fig = ff.create_annotated_heatmap(
            z=df_corr_round.to_numpy(),
            x=df_corr.columns.tolist(),
            y=df_corr.index.tolist(),
            zmax=1, zmin=-1,
            showscale=True,
            hoverongaps=True
            )
# add title
fig.update_layout(title_text='<i><b>Correlation round</b></i>')

但是当我将鼠标悬停在文本上时,变通方法也会使文本圆整。我想在充分的细节悬停文本,而显示文本是圆的。
我可以在不改变输入数据框的情况下在每个单元格上显示更少的数字吗?

vuktfyat

vuktfyat1#

我只能假设您正在从一个列表列表中构建ff.create_annotated_heatmap(),就像在Annotated Heatmaps in Python下的文档中所做的那样。如果你使用的是pandas数据框,也不用担心。下面的完整代码片段将向您展示如何从pandas Dataframe 构建correlation matrix,其中包含多个股票时间序列px.data.stocks,然后使用df.values.tolist()创建列表列表以构建带注解的热图。如果你正在做类似的事情,那么构建注解的一种方法就是定义一个这样的文本:

z_text = [[str(y) for y in x] for x in z]

然后,你需要得到你想要的数字个数,就是使用round():

z_text = [[str(round(y, 1)) for y in x] for x in z]

正如你在下面看到的,这种方法(1)不会像df_corr.round()那样改变源 Dataframe ,(2)在图中只显示1个数字,(3)在悬停时显示更长的数字格式。在图像中,我悬停在MSFT / FB = 0.5

完整代码:

import plotly.express as px
import plotly.figure_factory as ff
import pandas as pd

df = px.data.stocks()#.tail(50)
df = df.drop(['date'], axis = 1)
dfc = df.corr()
z = dfc.values.tolist()

# change each element of z to type string for annotations
# z_text = [[str(y) for y in x] for x in z]
z_text = [[str(round(y, 1)) for y in x] for x in z]

# set up figure 
fig = ff.create_annotated_heatmap(z, x=list(df.columns),
                                     y=list(df.columns),
                                     annotation_text=z_text, colorscale='agsunset')

# add title
fig.update_layout(title_text='<i><b>Confusion matrix</b></i>',
                  #xaxis = dict(title='x'),
                  #yaxis = dict(title='x')
                 )

# add custom xaxis title
fig.add_annotation(dict(font=dict(color="black",size=14),
                        x=0.5,
                        y=-0.15,
                        showarrow=False,
                        text="",
                        xref="paper",
                        yref="paper"))

# add custom yaxis title
fig.add_annotation(dict(font=dict(color="black",size=14),
                        x=-0.35,
                        y=0.5,
                        showarrow=False,
                        text="",
                        textangle=-90,
                        xref="paper",
                        yref="paper"))

# adjust margins to make room for yaxis title
fig.update_layout(margin=dict(t=50, l=200))

# add colorbar
fig['data'][0]['showscale'] = True
fig.show()
6jygbczu

6jygbczu2#

我手头没有数据,所以我还没能检查执行情况,但我认为下面的代码可以工作。请参阅official reference

df_corr_round = df_corr.round(3)
fig = ff.create_annotated_heatmap(
            z=df_corr,
            x=df_corr.columns.tolist(),
            y=df_corr.index.tolist(),
            zmax=1, zmin=-1,
            showscale=True,
            hoverongaps=True,
            annotation_text=df_corr_round.to_numpy(),
            )
# add title
fig.update_layout(title_text='<i><b>Correlation round</b></i>')
stszievb

stszievb3#

您应该添加".round()"方法。您可以对 Dataframe 执行相同的操作。
下面的代码适用于具有非舍入矩阵值的值,其中包含plotly.express:

import plotly.express as px
import numpy as np

fig = px.imshow(
    np.random.rand(4, 4),
    text_auto=True
)
fig.show()

The graph with non-rounded values
现在用rounded:

import plotly.express as px
import numpy as np

fig = px.imshow(
    np.random.rand(4, 4).round(2),
    text_auto=True
)
fig.show()

With rounded values

dxpyg8gm

dxpyg8gm4#

使用update_traces设置texttemplatehovertemplate。还需要声明text_auto=True

fig = px.imshow(
    matrix,  
    text_auto=True, 
    aspect="auto", 
    color_continuous_scale='Viridis'

fig.update_traces(
    texttemplate='%{z:.2f}',
    hovertemplate=("%{x}<br>%{y}<br><b>correlation: %{z}</b><extra></extra>")
)

相关问题