3

How to add hover data to the argument of fig.add_scatter in plotly? It belongs to fig = px.scatter, but I used this for a point to provide name argument. Thank you

Here is the data:

file:
1       27  10  20.10.2021
2       10  11  21.10.2021
3       10  2   28.10.2021    
4       13  8   05.11.2021
5       17  5   17.11.2021

Here is the code:

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

datum = np.loadtxt('file', unpack=True, dtype='str', usecols=[3])
cislo, K, H = np.loadtxt('file', unpack=True, usecols=[0, 1, 2])

d = {'Datum': datum, 'B': K, 'C': H, 'cislo': cislo}
df = pd.DataFrame(data=d)

fig = px.scatter(df, x=[-100], y=[100]) # hover_data=['datum']

fig.add_scatter(x=df['cislo'], y=df['C'], hoverinfo='skip', mode="markers", marker=dict(size=10,color='Purple'), name = 'C')

fig.add_scatter(x=df['cislo'], y=df['B'], hoverinfo='skip', mode="markers", marker=dict(size=10,color='Green'), name = 'B')

fig.update_traces(
    hovertemplate="<br>".join([
        "<b>Value:</b>       %{y:.0f}",
        "<b>Date:</b>              %{customdata[0]}",
     ])
    )
fig.update_traces(mode='lines+markers')

layout = go.Layout(
    yaxis_range=[0,28],
    xaxis_range=[0.5,6],
    legend=dict(
        yanchor="top",
        y=0.95,
        xanchor="left",
        x=0.73,
     ),
    hoverlabel=dict(
        bgcolor="White",
    )
)
fig.layout = layout
fig.show()

1 Answer 1

3
  • given the way you have structured hovertemplate the following works.
  • add_scatter() is core API method (graph objects) rather than plotly express
import plotly.express as px
import numpy as np
import pandas as pd
import plotly.graph_objects as go

with open("file", "w") as f:
    f.write("""1       27  10  20.10.2021
2       10  11  21.10.2021
3       10  2   28.10.2021    
4       13  8   05.11.2021
5       17  5   17.11.2021""")

datum = np.loadtxt("file", unpack=True, dtype="str", usecols=[3])
cislo, K, H = np.loadtxt("file", unpack=True, usecols=[0, 1, 2])

d = {"Datum": datum, "B": K, "C": H, "cislo": cislo}
df = pd.DataFrame(data=d)

fig = px.scatter(df, x=[-100], y=[100])  # hover_data=['datum']

fig.add_scatter(
    x=df["cislo"],
    y=df["C"],
    customdata=df["Datum"].values.reshape([len(df), 1]),
    hoverinfo="skip",
    mode="markers",
    marker=dict(size=10, color="Purple"),
    name="C",
)

fig.add_scatter(
    x=df["cislo"],
    y=df["B"],
    customdata=df["Datum"].values.reshape([len(df), 1]),
    hoverinfo="skip",
    mode="markers",
    marker=dict(size=10, color="Green"),
    name="B",
)

fig.update_traces(
    hovertemplate="<br>".join(
        [
            "<b>Value:</b>       %{y:.0f}",
            "<b>Date:</b>              %{customdata[0]}",
        ]
    )
)
fig.update_traces(mode="lines+markers")

layout = go.Layout(
    yaxis_range=[0, 28],
    xaxis_range=[0.5, 6],
    legend=dict(
        yanchor="top",
        y=0.95,
        xanchor="left",
        x=0.73,
    ),
    hoverlabel=dict(
        bgcolor="White",
    ),
)
fig.layout = layout
fig
Sign up to request clarification or add additional context in comments.

2 Comments

How to use in customdata=df["Datum"].values.reshape([len(df), 1]), two lists of values? I tried something like df["Datum", "Datum2"].values.reshape([len(df), 1]) or do the reshape for ([len(df), 2]), but it is wrong.
@Carly 1. define column: df["Datum2"] = (pd.to_datetime(df["Datum"], infer_datetime_format=True) + pd.Timedelta(days=3)).dt.strftime("%d.%m.%Y") 2. put into custom data customdata=df.loc[:,["Datum","Datum2"]].values.reshape([len(df),2]), 3. update hover template hovertemplate="<br>".join( [ "<b>Value:</b>%{y:.0f}", "<b>Date:</b>%{customdata[0]}", "<b>Date2:</b>%{customdata[1]}", ] )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.