简体   繁体   中英

Hover format for hover data in Plotly | Python

I'm trying to format the hover values to show only 2 decimal place for a graph. I was able to format values corresponding x and y values to 2 decimal place. My question is how to format the additional hover data to 2 decimal place?

import numpy as np
import plotly.express as px

x = 0.01001*np.arange(5)
y = 0.5*x
hover_data = [y*3]

fig = px.area(x=x, y=y, hover_data=hover_data)
fig.update_layout(
    xaxis=dict(hoverformat='.2f'),
    yaxis=dict(hoverformat='.2f')
)
fig.show()

The image below may clarify what I mean: 在此处输入图像描述

In your case, you can use:

fig.data[0].hovertemplate = 'x=%{x}<br>y=%{y}<br>hover_data_0=%{customdata[0]:.2f}<extra></extra>'

A more flexible approach for multiple traces:

fig.update_traces(hovertemplate = 'x=%{x}<br>y=%{y}<br>hover_data_0=%{customdata[0]:.2f}<extra></extra>')

If you're the kind of pythonista that prefers lambda functions, you can also go for:

fig.for_each_trace(lambda t: t.update(hovertemplate = 'x=%{x}<br>y=%{y}<br>hover_data_0=%{customdata[0]:.2f}<extra></extra>'))

在此处输入图像描述

Complete code

import numpy as np
import plotly.express as px

x = 0.01001*np.arange(5)
y = 0.5*x
hover_data = [y*3]

fig = px.area(x=x, y=y, hover_data=hover_data)
fig.update_layout(
    xaxis=dict(hoverformat='.2f'),
    yaxis=dict(hoverformat='.2f')
)

fig.data[0].hovertemplate = 'x=%{x}<br>y=%{y}<br>hover_data_0=%{customdata[0]:.2f}<extra></extra>'

fig.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM