Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotly python add annotation to display all column values at every point

I am trying to plot all column values at each point when we hover over a data point in plotly

My code is as follows

import plotly.graph_objects as go
import plotly.io as pio
from plotly.subplots import make_subplots
import pandas as pd

# data
pio.templates.default = "plotly_white"
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
df_s = df[['Date','AAPL.Open','AAPL.High','AAPL.Low','dn','mavg'
        ]]
df_s = df_s.set_index('Date')
df_s.tail()
cols = df_s.columns
ncols = len(cols)

# subplot setup
fig = make_subplots(rows=ncols, cols=1, shared_xaxes=True)

for i, col in enumerate(cols, start=1):
    fig.add_trace(go.Scatter(x=df_s[col].index, y=df_s[col].values, name=df_s[col].name), row=i, col=1)

fig.update_layout(
    autosize=False,
    width=1200,
    height=800,)

    
fig.show()

Currently when I hover over the datapoint it shows value for that column alone. I am interested in seeing Values for 'Date','AAPL.Open','AAPL.High','AAPL.Low','dn','mavg' these columns at a particular row whenever I hover over anyplot

enter image description here

I tried add_annotations with no luck. Is there a way of doing it? Thank you in advance

like image 584
anonymous13 Avatar asked Oct 29 '25 04:10

anonymous13


1 Answers

As @Marco_CH pointed out, this exact feature doesn't exist in Plotly. However, you can try using a unified hovermode on the x-axis so there is only one hoverbox, and remove the date from each hovertemplate since it's already shown at the top of the hoverbox.

import pandas as pd
import plotly.express as px 

df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv")
df1 = df.melt(id_vars=['Date']+list(df.keys()[5:]), var_name='AAPL')
fig = px.line(df1, x='Date', y='value', color='AAPL' )

## remove date from each hovertemplate
for fig_data in fig.data:
    fig_data['hovertemplate'] = fig_data['hovertemplate'].replace("<br>Date=%{x}","")
fig.update_layout(hovermode="x unified")
    
fig.show()

enter image description here

like image 54
Derek O Avatar answered Oct 31 '25 10:10

Derek O



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!