python Plotly:在悬停模板中包含附加数据

fcy6dtqo  于 2023-03-16  发布在  Python
关注(0)|答案(5)|浏览(218)

x1c 0d1x悬停模板= '洲:%{df ['大陆']}
'+ '国家:%{df ['国家']}
“+”gdpPercap:%{x:,.4f}
“+”寿命:%{y}“+”“
我尝试使用悬停模板来自定义悬停信息。但是我不能让它显示我想要的。我得到x & y工作良好。我不知道如何添加其他字段到悬停模板虽然。任何帮助将不胜感激。

import numpy as np
df = df[df['year'] == 1952]
customdata = np.stack((df['continent'], df['country']), axis=-1)
fig = go.Figure()
for i in df['continent'].unique():
    df_by_continent = df[df['continent'] == i]
    fig.add_trace(go.Scatter(x=df_by_continent['gdpPercap'], 
                         y=df_by_continent['lifeExp'],
                         mode='markers',
                         opacity=.7,
                         marker = {'size':15},
                         name=i,
                         hovertemplate=
                            'Continent: %{customdata[0]}<br>'+
                            'Country: %{customdata[1]}<br>'+
                            'gdpPercap: %{x:,.4f} <br>'+
                            'lifeExp: %{y}'+
                             '<extra></extra>',
                            ))
fig.update_layout(title="My Plot",
                 xaxis={'title':'GDP Per Cap',
                       'type':'log'},
                 yaxis={'title':'Life Expectancy'},
                )
fig.show()

更新了更多的代码。第一个答案不工作,只是返回comdata的文本值。

r1wp621o

r1wp621o1#

请参阅下面的示例,了解如何根据问题中包含的代码将customdata与多个跟踪一起使用。请注意,实际上需要将customdata添加到图形跟踪中,以便在hovertemplate中使用它,这也显示在Derek O的答案中。

import numpy as np
import pandas as pd
import plotly.graph_objects as go

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv')
df = df[df['year'] == 1952]

fig = go.Figure()

for continent in df['continent'].unique():

    df_by_continent = df[df['continent'] == continent]

    fig.add_trace(
        go.Scatter(
            x=df_by_continent['gdpPercap'],
            y=df_by_continent['lifeExp'],
            customdata=np.stack((df_by_continent['country'], df_by_continent['pop']), axis=-1),
            mode='markers',
            opacity=0.7,
            marker={'size': 15},
            name=continent,
            hovertemplate='<b>Country</b>: %{customdata[0]}<br>' +
                          '<b>Population</b>: %{customdata[1]:,.0f}<br>' +
                          '<b>GDP</b>: %{x:$,.4f}<br>' +
                          '<b>Life Expectancy</b>: %{y:,.2f} Years' +
                          '<extra></extra>',
        )
    )

fig.update_layout(
    xaxis={'title': 'GDP Per Cap', 'type': 'log'},
    yaxis={'title': 'Life Expectancy'},
)

fig.write_html('fig.html', auto_open=True)

0md85ypi

0md85ypi2#

对于hovertemplate字符串中除了{x}{y}之外的任何其他变量,您需要创建一个名为customdata的变量,它是DataFrame列的numpy数组(在您的示例中是df['continent'], df['country']),并将customdata=customdata传递给fig.update_layout,这是@empet在他的Plotly论坛答案here中建议的。
您可以尝试以下操作:

import numpy as np
import pandas as pd
import plotly.express as px

df = px.data.gapminder()

customdata = np.stack((df['continent'], df['country']), axis=-1)

fig = px.scatter(df, x="gdpPercap", y="lifeExp")

hovertemplate = ('Continent: %{customdata[0]}<br>' + 
    'Country: %{customdata[1]}<br>' + 
    'gdpPercap: %{x:,.4f} <br>' + 
    'lifeExp: %{y}' + 
    '<extra></extra>')

fig.update_traces(customdata=customdata, hovertemplate=hovertemplate)
fig.show()

klr1opcd

klr1opcd3#

以上答案的变体,仅使用Pandas/Python:

customdata = list(df[['continent','country']].to_numpy())

然后使用引用自定义数据的模板构建图形,如其他答案所示。以下是Scatter 3D的一个示例,并添加来自数据框两列的数据:

import plotly.graph_objects as go

customdata_set = list(df[['transaction','type']].to_numpy())

fig = go.Figure(
    data=[go.Scatter3d(x=df.time,
                       y=df.source,
                       z=df.dest,
                       hovertemplate='<i>Source:</i>: %{y:i}<br>' +
                       '<i>Destination:</i>: %{z:i}<br>' +
                       '<i>Amount:</i>: $%{text}<br>' +
                       '<i>Txn #:</i>: %{customdata[0]}<br>' +
                       '<i>Txn Type:</i>: %{customdata[1]}<br>' +
                       '<i>Date:</i>: %{x|%Y-%m-%d}',
                       text=(df.amount).to_numpy(),
                       customdata = customdata_set,
                       mode='markers',
                       marker=dict(
                            color=moat_sql.tx_amount,
                            size=4,
                            opacity=.8,
                            showscale=True,
                            colorscale='Viridis',
                            colorbar=dict(
                                title=dict(text='Log Txn Amount',
                                           side='bottom',
                                           font={'color': 'red'}
                                           )
                            )
    )
    )]
)
xdyibdwo

xdyibdwo4#

不用customdata + hovertemplate,你可以直接把格式化的文本传递给text参数,我发现这更简单,也更强大--例如,如果你不想让所有元素都有完全相同的格式。
这是可行的

text = your_df.map(
    lambda row: f'<i>Source:</i>: %{row.source:i}<br>' +
                    f'<i>Destination:</i>: %{row.z:i}<br>' +
                    f'<i>Amount:</i>: $%{row.amount}<br>' +
                    f'<i>Txn #:</i>: %{row.txn}<br>' +
                    f'<i>Txn Type:</i>: %{row.txn_type}<br>' +
                    f'<i>Date:</i>: %{row.date|%Y-%m-%d}',
    axis='columns'
)

go.Scatter3d(
   ...,
   text=text,
   ...
)

text元素不支持完整的HTML,但我看到它至少支持<br><b>标签,它似乎不支持<h1>, <nbsp>, <hr>标签。
我相信hovertemplate也是如此。

qzlgjiam

qzlgjiam5#

下面是一个使用Plotly.js的Javascript示例,以防有人查找它。:

<!DOCTYPE html>
<html>
<head><script src="https://cdn.plot.ly/plotly-2.14.0.min.js"></script></head>
<body>
    <div id="myDiv" style="width: 100%; height: 100%;"></div>
    <script>
        // Define custom data
        const customData = [
            {
                x: [1, 2, 3],
                y: [4, 5, 6],
                z: ["Potato", "Banana", "Tomato"]
            }
        ];

        // Define custom hovertemplate
        const customHovertemplate = "X: %{x}<br>Y: %{y}<br>Z: %{customdata}";

        // Define trace using custom data and hovertemplate
        const trace = {
            x: customData[0].x,
            y: customData[0].y,
            customdata: customData[0].z,
            mode: "markers",
            marker: { color: "blue", size: 12 },
            type: "scatter",
            hovertemplate: customHovertemplate
        };

        Plotly.newPlot("myDiv", [trace]);
    </script>
</body>
</html>

相关问题