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

How to show text on a heatmap with Plotly?

我正在尝试将 z 项目显示为 Plotly 热图上的文本。我正在使用最新版本 (5.5.0) 并遵循 Plotly Heatmaps 网页 (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}
                                       )
                      )

当我在网页中呈现我的应用程序时,我看到的是:

但是在他们的网站上它显示了标签:

当我 运行 我的应用程序时,我没有收到任何错误,当我将鼠标悬停在热图上时,标签确实会显示,但文本没有按应有的方式显示在热图上。由于我使用的是他们的确切示例,因此我不明白可能出了什么问题。有什么想法吗?

[编辑]:这似乎是达世币的一个问题。当我以交互方式 运行 示例时,我确实得到了文本标签。但是我的应用程序是 Dash 应用程序的一部分,这就是我看不到渲染标签的地方。


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

破折号

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