如何在Plotly热力图上显示文本?

8
我将尝试在 Plotly 热图中将 z 项目显示为文本。我正在使用最新版本(5.5.0),并且遵循 Plotly 热图网页(https://plotly.com/python/heatmaps/) 上展示的精确示例,可以查看底部的“热图点上的文本”部分。
我的代码与他们的示例代码相同,如下:
figHeatmap = go.Figure(
                       data=go.Heatmap(
                                       z=[[1,20,30], [20,1,60], [30,60,1]], 
                                       text=[['1','2','3'],['4','5','6'],['7','8','9']], 
                                       texttemplate="%{text}", 
                                       textfont={"size":20}
                                       )
                      )

当我在网页上渲染我的应用程序时,我看到的是这样的:enter image description here。但是他们的网站上显示了标签:enter image description here。 当我悬停在热图上时,它确实显示标签,但文本不像应该显示在热图上那样。由于我正在使用他们的示例,我不明白可能出了什么问题。有什么想法吗? [编辑]:这似乎是Dash的问题。当我交互式运行示例时,我确实会得到文本标签。但我的应用程序是Dash应用程序的一部分,我在那里看不到呈现的标签。

您所参考的官方文档示例中有关于注释的代码,但是您的代码中却没有。请添加注释代码。text=[['one',...]]。 - r-beginners
我确实有那个,只是为了让在这里发布的问题更容易阅读,我将其缩短了。您可以看到我引用的字符串数量与同一列表格式中的示例相同。 - K-83Rick
当交互式运行时,这确实按预期工作。但是,在尝试在Dash应用程序中实现相同效果时会出现问题。我已经在我的问题中添加了一个编辑语句来澄清这一点。 - K-83Rick
1个回答

8

import plotly.express as px
import plotly.graph_objects as go
import inflect

p = inflect.engine()
df = px.data.medals_wide(indexed=True)
fig = px.imshow(df, text_auto=True)
fig2 = go.Figure(fig.data, fig.layout)
fig2 = fig2.update_traces(text=df.applymap(p.number_to_words).values, texttemplate="%{text}", hovertemplate=None)

fig.show()
fig2.show()

enter image description here

dash

  • 请参阅https://dash.plotly.com/external-resources 中的Controlling the Plotly.js Version Used by dcc.Graph,以控制所使用的 plotly.js 版本
  • dash 2.0.0 包含了一个尚未支持texttemplateplotly.js 版本
  • 以下代码展示如何进行覆盖
import numpy as np
import dash
import plotly.graph_objects as go
import plotly.express as px
from dash.dependencies import Input, Output, State
from jupyter_dash import JupyterDash
import inflect

# Build App
app = JupyterDash(__name__, external_scripts=["https://cdn.plot.ly/plotly-2.8.3.min.js"])
app.scripts.config.serve_locally = False
app.layout = dash.html.Div(
    [
        dash.dcc.Interval(id="run", max_intervals=1),
        dash.dcc.Graph(id="fig"),
    ]
)


def hm():
    p = inflect.engine()
    df = px.data.medals_wide(indexed=True)
    fig = px.imshow(df, text_auto=True)
    fig2 = go.Figure(fig.data, fig.layout)
    fig2 = fig2.update_traces(
        text=df.applymap(p.number_to_words).values,
        texttemplate="%{text}",
        hovertemplate=None,
    )
    return fig2.update_layout(title=f"dash: {dash.__version__}")


@app.callback(Output("fig", "figure"), Input("run", "n_intervals"))
def createFig(n):
    return hm()


# Run app and display result inline in the notebook
app.run_server(mode="inline")

谢谢您。我同意在交互式运行时这个程序是有效的。然而,在Dash中实现时,它并没有按照预期工作。我已经在我的问题中添加了一个编辑声明来澄清这一点。 - K-83Rick
更新 - 我遇到了与Jupyter相似的问题。必须使用正确版本的Plotly JS库。 - Rob Raymond
谢谢,我从来没有想到过要进行完整的Jupyter重置。 - Kermit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接