add_scatter 和自定义数据

add_scatter and custom data

如何使用悬停标签中的悬停数据添加 fig.add_scatter?

最小代码无效。

我需要添加另一组与第一个悬停模板相同的数据。

非常感谢

import numpy as np
import pandas as pd
a, b, c = [1, 2], [1, 5], [5, 6]
d, e, f = [5, 5], [4, 4], [5, 5]
s1 = ['A', 'F']
s2 = ['V', 'T']

d = {'a': a, 'b': b, 'c': c, 's1':s1}
df = pd.DataFrame(data=d)

d2 = {'d': d, 'e': e, 'f': f, 's2':s2}
df2 = pd.DataFrame(data=d2)

fig = px.scatter(df, x='a', y='b', hover_data=['c', 's1'], color='s1', color_discrete_sequence=["green", "navy"])

fig.add_scatter(x=df2['d'], y=df2['e'], customdata=['f', 's2'], mode="markers", marker=dict(size=10,color='Purple'), name = 'A')  # ------> these custom data are not in label, there is just %{customdata[1]}

fig.update_traces(
    hovertemplate="<br>".join([
        "<b>G:</b>               %{x:.3f}",
        "<b>R:</b>      %{y:.6f}<extra></extra>", 
        "<b>D:</b>            %{customdata[1]}",
        "<b>E:</b>              %{customdata[0]}",
     ])
    )


fig.update_xaxes(title_font_family="Trebuchet")

fig.update_traces(marker=dict(size=9),
                  selector=dict(mode='markers'))

fig.show()

创建 df2 时出错。假设了您要实现的目标。下面使 hovertext 工作。

import numpy as np
import pandas as pd

a, b, c = [1, 2], [1, 5], [5, 6]
d, e, f = [5, 5], [4, 4], [5, 5]
s1 = ["A", "F"]
s2 = ["V", "T"]

d = {"a": a, "b": b, "c": c, "s1": s1}
df = pd.DataFrame(data=d)

d2 = {"d": d, "e": e, "f": f, "s2": s2}
# SO question invalid !!!
# df2 = pd.DataFrame(data=d2)
# try this
df2 = pd.DataFrame(d).join(pd.DataFrame({k:v for k,v in d2.items() if k!="d"}))

fig = px.scatter(
    df,
    x="a",
    y="b",
    hover_data=["c", "s1"],
    color="s1",
    color_discrete_sequence=["green", "navy"],
)

fig.add_scatter(
    x=df2["a"],
    y=df2["e"],
    customdata=df2.loc[:,["f", "s2"]].values.reshape([len(df2),2]),
    mode="markers",
    marker=dict(size=10, color="Purple"),
    name="A",
)  # ------> these custom data are not in label, there is just %{customdata[1]}

fig.update_traces(
    hovertemplate="<br>".join(
        [
            "<b>G:</b>               %{x:.3f}",
            "<b>R:</b>      %{y:.6f}<extra></extra>",
            "<b>D:</b>            %{customdata[1]}",
            "<b>E:</b>              %{customdata[0]}",
        ]
    )
)


fig.update_xaxes(title_font_family="Trebuchet")

fig.update_traces(marker=dict(size=9), selector=dict(mode="markers"))

fig.show()