Home > Software design >  add_scatter and custom data
add_scatter and custom data

Time:03-17

How to add fig.add_scatter with hover data that is in the hover label?

The minimal code is not working.

I need to add another set of data with the same hover template as the first one.

Many thanks

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

CodePudding user response:

There are errors in creating df2. Have assumed what you are trying to achieve. Below makes hovertext work.

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