Hover template for a scatter chart with single X axis and six Y-axis

Hi,
Need advice to bring all Y-Parameter values under same time stamp when mouse over on one of the Y-axis line .Currently when i am doing able to get only three parameters on the line pointer ,after repeated attempts could not achieve. Request your help and appreciate in advance.
Code as below for Plotly chart generation and also current output screen shot.

df=dataset
from_date = df['Date_Time'].min()
to_date = df["Date_Time"].max()

import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
from datetime import date, time,datetime,timedelta

# Function to plot time series with Input dataframe,from_date & to_date- Multiple y axis with common slider for the x axis -Using date_time
def plot_range_KW_AC_status_temp(df,from_date,to_date):
      
      title_name = "Minute_wise_Tubewell_status_parameter_trend"
      fig = go.Figure()

      fig = make_subplots(rows=6, cols=1,
                          shared_xaxes=True,
                          vertical_spacing=0.2)
      fig.add_trace(go.Scatter(x=df['Date_Time'], y=df['Flow'],line = dict(color = "#ff0000", width=1),
    hovertemplate='%{y:.2f} Flow<br>%{customdata[1]:.2f} Pressure <br>%{customdata[2]:.2f} Current<br>{customdata[3]:.2f} KWH<br>{customdata[4]:.2f} Pump_Status<br>{customdata[5]:.2f} Water_Level<br>%{x}<extra></extra>',
                    customdata=df[['Flow','Pressure','Current','KWH','Pump_Status','Water_Level']]),
                  row=1, col=1)
      fig.add_trace(go.Scatter(x=df['Date_Time'], y=df['Pressure'],line = dict(color = "#FF00FF", width=1),
    hovertemplate='%{y:.2f} Pressure<br>%{customdata[0]:.2f} Flow <br>%{customdata[2]:.2f} Current<br>{customdata[3]:.2f} KWH<br>{customdata[4]:.2f} Pump_Status<br>{customdata[5]:.2f} Water_Level<br>%{x}<extra></extra>',
                    customdata=df[['Flow','Pressure','Current','KWH','Pump_Status','Water_Level']]),
                  row=2, col=1)
      fig.add_trace(go.Scatter(x=df['Date_Time'], y=df['Current'],line = dict(color = "#122BFB", width=1),
    hovertemplate='%{y:.2f} Current<br>%{customdata[0]:.2f} Flow <br>%{customdata[1]:.2f} Pressure<br>{customdata[3]:.2f} KWH<br>{customdata[4]:.2f} Pump_Status<br>{customdata[5]:.2f} Water_Level<br>%{x}<extra></extra>',
                    customdata=df[['Flow','Pressure','Current','KWH','Pump_Status','Water_Level']]),
                  row=3, col=1)

      fig.add_trace(go.Scatter(x=df['Date_Time'], y=df['KWH'],line = dict(color = "#55A219", width=1),
    hovertemplate='%{y:.2f} KWH<br>%{customdata[0]:.2f} Flow <br>%{customdata[1]:.2f} Pressure <br>{customdata[2]:.2f} Current<br>{customdata[4]:.2f} Pump_Status<br>{customdata[5]:.2f} Water_Level<br>%{x}<extra></extra>',
                    customdata=df[['Flow','Pressure','Current','KWH','Pump_Status','Water_Level']]),
                  row=4, col=1)
      fig.add_trace(go.Scatter(x=df['Date_Time'], y=df['Pump_Status'],line = dict(color = "#10CCE2", width=1),
    hovertemplate='%{y:.2f} Pump_Status<br>%{customdata[0]:.2f} Flow <br>%{customdata[1]:.2f} Pressure<br>{customdata[2]:.2f} Current <br>{customdata[3]:.2f} KWH <br>{customdata[5]:.2f} Water_Level <br>%{x}<extra></extra>',
                    customdata=df[['Flow','Pressure','Current','KWH','Pump_Status','Water_Level']]),
                  row=5, col=1)
      fig.add_trace(go.Scatter(x=df['Date_Time'], y=df['Water_Level'],line = dict(color = "#EF4D0B", width=1),
    hovertemplate='%{y:.2f} Water_Level<br>%{customdata[0]:.2f} Flow <br>%{customdata[1]:.2f} Pressure<br>{customdata[2]:.2f} Current<br>{customdata[3]:.2f} KWH <br>{customdata[4]:.2f} Pump_Status<br>%{x}<extra></extra>',
                    customdata=df[['Flow','Pressure','Current','KWH','Pump_Status','Water_Level']]),
                  row=6, col=1)

      fig.update_layout(autosize=True,height=600, width=1000,
                        title_text=title_name,
                        xaxis_rangeslider_thickness = 0.1)

      fig.update_layout(
      xaxis=dict(
        autorange=True,
        range=[from_date,to_date],
        rangeslider=dict(
            autorange=True,
            range=[from_date,to_date],
                    ),
        type="date"
      ),
        yaxis=dict(
        anchor="x",
        autorange=True,
        domain=[0, 0.25],

        linecolor="#ff0000",
        mirror=True,
        range=[df['Flow'].min(), df['Flow'].max()],
        showline=True,
        side="right",
        tickfont={"color": "#ff0000"},
        tickmode="auto",
        ticks="",
        titlefont={"color": "#ff0000"},
        type="linear",
        zeroline=True,
        title="Flow",
        position=0.0
        ),
        yaxis2=dict(
        anchor="x",
        autorange=True,
        domain=[0.25,0.5],
        linecolor="#FF00FF",
        mirror=True,
        range=[df['Pressure'].min(), df['Pressure'].max()],
        showline=True,
        side="right",
        tickfont={"color": "#FF00FF"},
        tickmode="auto",
        ticks="",
        titlefont={"color": "#FF00FF"},
        type="linear",
        zeroline=True,
        title="Pressure",

        ),
       yaxis3=dict(
        anchor="x",
        autorange=True,
        domain=[0.5,0.75],
        linecolor="#122BFB",
        mirror=True,
        range=[df['Current'].min(), df['Current'].max()],
        showline=True,
        side="right",
        tickfont={"color": "#122BFB"},
        tickmode="auto",
        ticks="",
        titlefont={"color": "#122BFB"},
        type="linear",
        zeroline=True,
        title="Current",

        ),
         yaxis4=dict(
        anchor="x",
        autorange=True,
        domain=[0.75,0.85],
        linecolor="#55A219",
        mirror=True,
        range=[df['KWH'].min(), df['KWH'].max()],
        showline=True,
        side="right",
        tickfont={"color": "#55A219"},
        tickmode="auto",
        ticks="",
        titlefont={"color": "#55A219"},
        type="linear",
        zeroline=True,
        title="KWH",

        ),
        yaxis5=dict(
        anchor="x",
        autorange=True,
        domain=[0.85,0.9],
        linecolor="#10CCE2",
        mirror=True,
        range=[df['Pump_Status'].min(), df['Pump_Status'].max()],
        showline=True,
        side="right",
        tickfont={"color": "#10CCE2"},
        tickmode="auto",
        ticks="",
        titlefont={"color": "#10CCE2"},
        type="linear",
        zeroline=True,
        title="Pump_Status",

        ),
         yaxis6=dict(
        anchor="x",
        autorange=True,
        domain=[0.9,1],
        linecolor="#EF4D0B",
        mirror=True,
        range=[df['Water_Level'].min(), df['Water_Level'].max()],
        showline=True,
        side="right",
        tickfont={"color": "#EF4D0B"},
        tickmode="auto",
        ticks="",
        titlefont={"color": "#EF4D0B"},
        type="linear",
        zeroline=True,
        title="Water_Level",

        ),
      )
      fig.update_xaxes(automargin=True)
      fig.update_yaxes(automargin=True)


      # Update layout
      fig.update_layout(
          autosize=False,
          dragmode="zoom",
          hovermode='x unified',
          updatemenus=[
        {
            'type': 'buttons',
            'showactive': False,
            'buttons': [
                {
                    'label': 'Show All Y-Axis Values',
                    'method': 'relayout',
                    'args': ['hovermode', 'x unified']
                },
                {
                    'label': 'Reset Hover',
                    'method': 'relayout',
                    'args': ['hovermode', 'closest']
                }
            ]
        }
    ],
           height=800,
           width=1500,

          margin=dict(
              l=20,
              t=30,
              b=20,
              r=20,

              autoexpand=True
          ),
      )


      fig.show()
      # fig.write_html("C:\\Power BI Related\\ test\\"+title_name+".html")



plot_range_KW_AC_status_temp(df,from_date,to_date)

Hi @jaikishank I think you are searching for Unified hovermode.

I have used the “unified” hove mode only but iam unable to get all the y-axis data points against the x-axis time stamp together in one template. That;s where iam struck.If u see the appended image i get only three y-axis parameters,balance three y-axis unable to get them on the template.My code just repeats the text only and not the values of the parameters.

Does this help?

import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np

names = ['Current','Flow' ,'Pressure','KWH','Pump_Status','Water_Level']
y_vals = np.random.randint(1, 10,size=(10, len(names)))

fig = make_subplots(rows=len(names), cols=1)

for idx, name in enumerate(names, start=1):
    fig.add_traces(
        go.Scatter(
            x=np.arange(10), 
            y=y_vals[:, idx-1], 
            mode='lines',
            customdata=y_vals,
            name=name
    ), 
    rows=idx, 
    cols=1
    )                    ,

hover = ''.join([f'{name}: '+ '%{customdata[' + f'{idx}]' +'}<br>' for idx, name in enumerate(names)])

fig.update_layout(hovermode="x unified", height=600)
fig.update_traces(hovertemplate=hover + '<extra></extra>', xaxis='x1')

grafik

1 Like

Thanks for your response and the detailed code. I customised now as per the requirement as below.

df=dataset
from_date = df[‘Date_Time’].min()
to_date = df[“Date_Time”].max()
import plotly.graph_objects as go
from plotly.subplots import make_subplots

def plot_range_KW_AC_status_temp(df, from_date, to_date):
title_name = “Minute_wise_Tubewell_status_parameter_trend”
names = [‘Flow’,‘Pressure’,‘Current’,‘KWH’,‘Pump_Status’,‘Water_Level’]
fig = make_subplots(rows=len(names), cols=1)
y_vals = df[names]
for idx, name in enumerate(names, start=1):
fig.add_traces(
go.Scatter(
x=df[‘Date_Time’],
y=y_vals[:, idx-1],
mode=‘lines’,
customdata=y_vals,
name=name
),
rows=idx,
cols=1
),
hover = ‘’.join([f’{name}: ‘+ ‘%{customdata[’ + f’{idx}]’ +‘}
’ for idx, name in enumerate(names)])
fig.update_layout(hovermode=“x unified”, height=600)
fig.update_traces(hovertemplate=hover + ‘’, xaxis=‘x1’)

fig.update_layout(autosize=False, xaxis_rangeslider_thickness=0.1,
                  xaxis=dict(autorange=True, range=[from_date, to_date],
                             rangeslider=dict(autorange=True, range=[from_date, to_date]),
                             type="date"))

fig.update_xaxes(automargin=True)
fig.update_yaxes(automargin=True)

fig.show()
fig.write_html("C:\\Power BI Related\\Tubewell test\\" + title_name + ".html")

Assuming df is your DataFrame

plot_range_KW_AC_status_temp(df, from_date, to_date)

But i am facing the below mentioned error while running the script.

TypeError: ‘(slice(None, None, None), 0)’ is an invalid key

During handling of the above exception, another exception occurred:

pandas.errors.InvalidIndexError: (slice(None, None, None), 0)

Please help me to resolve.

Resolved the issue which was very trivial in the end as per the code block in slicing thro index for variable y
image