【问题标题】:Correlation Heatmap in PlotlyPlotly 中的相关热图
【发布时间】:2021-06-08 20:43:55
【问题描述】:

我使用我喜欢的 Seaborn 创建了一个下三角相关热图。现在尝试使用 Plotly 创建相同的内容。不幸的是,无法像使用 Seaborn 那样对其进行微调。

names = ['U', 'V', 'W', 'X', 'Y', 'Z']
r = pd.DataFrame(index = names, columns = names)
r['U'] = np.array([1.0,   0.53,    0.26,  0.63, 0.52, 0.65] )
r['V'] = np.array([0.53,   1.0,   -0.17, 0.83, 1, 0.85])
r['W'] = np.array([0.26,  -0.17,    1.0,  0.04, -0.15, 0.09])
r['X'] = np.array([0.63, 0.83, 0.04, 1, 0.83, 0.80])
r['Y'] = np.array([0.52, 1, -0.15, 0.83, 1, 0.86])
r['Z'] = np.array([0.65, 0.85, 0.09, 0.80, 0.86, 1.0])

print(r)

import seaborn as sns

# sns.set_theme(style="white")

mask = np.triu(np.ones_like(r, dtype=bool))

# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))

# Generate a custom diverging colormap
cmap = sns.diverging_palette(230, 20, n=256, as_cmap=True)

# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(r, 
            mask=mask, 
            cmap=cmap, 
            vmax=1, 
            vmin = -.25,
            center=0,
            square=True, 
            linewidths=.5,
            annot = True,
            fmt='.2f', 
            annot_kws={'size': 10},
            cbar_kws={"shrink": .75})

plt.title('Asset Correlation Matrix')
plt.tight_layout()
ax.tick_params(axis = 'x', labelsize = 8)
ax.set_ylim(len(corr)+1, -1)
# plt.savefig('corrTax.png', dpi = 600)

plt.show()

我正在尝试使用 Plotly 创建它。到目前为止,这是我能做的。

mask = np.triu(np.ones_like(r, dtype=bool))
rLT = r.mask(mask)

heat = go.Heatmap(
    z = rLT,
    x = rLT.columns.values,
    y = rLT.columns.values,
    zmin = - 0.25, # Sets the lower bound of the color domain
    zmax = 1,
    xgap = 1, # Sets the horizontal gap (in pixels) between bricks
    ygap = 1,
    colorscale = 'RdBu'
)

title = 'Asset Correlation Matrix'

layout = go.Layout(
    title_text=title, 
    title_x=0.5, 
    width=600, 
    height=600,
    xaxis_showgrid=False,
    yaxis_showgrid=False,
    yaxis_autorange='reversed'
)

fig=go.Figure(data=[heat], layout=layout)
fig.show()

  • 我创建的 Seaborn 颜色图,我想在 Plotly 中创建类似的东西。我该怎么做?
  • 我能够控制轴标签的大小。
  • 希望将值放入每个框(seaborn 中的annot 选项),带有舍入选项

【问题讨论】:

    标签: python plot plotly seaborn heatmap


    【解决方案1】:

    您可以使用 plotly.figure_factory 中的 plotly 函数 create_annotated_heatmap 而不是普通的 plotly 热图。此函数直接接受 numpy 数组而不是数据帧。 Official Reference 这是我的解决方案

    corr = df.iloc.corr()
    mask = np.triu(np.ones_like(corr, dtype=bool))
    df_mask = corr.mask(mask)
    
    fig = ff.create_annotated_heatmap(z=df_mask.to_numpy(), 
                                      x=df_mask.columns.tolist(),
                                      y=df_mask.columns.tolist(),
                                      colorscale=px.colors.diverging.RdBu,
                                      hoverinfo="none", #Shows hoverinfo for null values
                                      showscale=True, ygap=1, xgap=1
                                     )
    
    fig.update_xaxes(side="bottom")
    
    fig.update_layout(
        title_text='Heatmap', 
        title_x=0.5, 
        width=1000, 
        height=1000,
        xaxis_showgrid=False,
        yaxis_showgrid=False,
        xaxis_zeroline=False,
        yaxis_zeroline=False,
        yaxis_autorange='reversed',
        template='plotly_white'
    )
    
    # NaN values are not handled automatically and are displayed in the figure
    # So we need to get rid of the text manually
    for i in range(len(fig.layout.annotations)):
        if fig.layout.annotations[i].text == 'nan':
            fig.layout.annotations[i].text = ""
    
    fig.show()
    

    您可以使用@ottovon 指定的zminzmax

    也可以使用基本的热图,但我想需要通过指定一些函数来手动完成注释。

    关于四舍五入注释,请参阅此Plotly: How to round display text in annotated heatmap but keep full format on hover? 线程。

    此外,您可以参考Official Docs 来确定 xticks 的大小,同样可以为 yticks 做同样的事情。我还没有实际实现它们,但它们应该可以正常工作。

    【讨论】:

      【解决方案2】:

      黛比。 这是您第一个问题的答案。

      我创建的 Seaborn 颜色图,我想在 Plotly 中创建类似的东西。我该怎么做?

      您可以使用内置的colorscales in Plotly,可以通过Heatmap构造函数中的参数colorscale进行设置。另外,你可以设置 Plotly 的主题来摆脱丑陋的背景

      import plotly.io as pio
      import plotly.express as px
      import plotly.graph_objects as go
      
      pio.templates.default = "plotly_white"
      
      go.Heatmap(
          z=corr.mask(mask),
          x=corr.columns,
          y=corr.columns,
          colorscale=px.colors.diverging.RdBu,
          zmin=-1,
          zmax=1
      )
      

      【讨论】:

      • 谢谢。可以把数字放在盒子里吗?
      猜你喜欢
      • 2021-09-22
      • 2022-09-25
      • 1970-01-01
      • 2019-05-23
      • 2019-07-18
      • 2020-03-22
      • 2017-12-05
      • 2021-02-22
      • 2011-09-05
      相关资源
      最近更新 更多