serdar_bay
serdar_bay

Reputation: 289

Plotly to show 2 decimal points when hovering over the chart, not nearest point

I am using Plotly to build a line chart, and when I hover over the line I would like it to display the x and y axis values up to 2 decimal points, instead of displaying the nearest data point on the line chart. To explain better, please see the example:

df = pd.DataFrame({'col1':[0.5,1.5,2.5], 'time':[2,3.5,4.5]})
def plot():            
   fig = go.Figure()
   fig.add_trace(go.Scatter(x = df['time'],
                            y = df['col1'], 
                            mode='lines', name = 'time plot', 
                            hovertemplate='%{x:.2f}: %{y:.2f}'))
   fig.update_layout(title='Plot', xaxis_tickformat = '.3f')

So, when I hover over the line, I can see x and y axis values to the nearest point from my dataset. I would like to be able to see 2 decimal points, for example, if I hover over the line, I want to see the points 2.11, 2.12 etc from the x-axis, even though they are not available on the data points.

Upvotes: 1

Views: 1151

Answers (1)

It_is_Chris
It_is_Chris

Reputation: 14113

I cannot think of a way to do this using plotly methods but I was able to think of a workaround by creating another line plot and setting the opacity to zero.

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

# your data
df = pd.DataFrame({'col1':[0.5,1.5,2.5], 'time':[2,3.5,4.5]})
# get the min and max X axis values
min_val, max_val = df['time'].agg([min, max])
# use np.arange to create the range with a step of .01
x = np.arange(min_val, max_val+.01, .01)
# create a zeros array of the same length
y = np.zeros(len(x))

# create your go.Figure object
fig = go.Figure()
# add your traces
fig.add_trace(go.Scatter(x=df['time'],
                         y=df['col1'],
                         name='time plot',
                         hovertemplate='%{x:.2f}: %{y:.2f}'))

fig.add_trace(go.Scatter(x=x,
                         y=y,
                         showlegend=False,  # remove line from legend
                         hoverinfo='x',
                         opacity=0))  # set opacity to zero so it does not display on the graph
# your layout
fig.update_layout(hovermode='x unified', xaxis_tickformat = '.2f', title='Plot')
fig.show()

enter image description here

Upvotes: 0

Related Questions