简体   繁体   English

Plotly 中 hover 数据的 Hover 格式 | Python

[英]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.我正在尝试格式化 hover 值以仅显示图形的小数点后 2 位。 I was able to format values corresponding x and y values to 2 decimal place.我能够将对应的 x 和 y 值格式化为小数点后 2 位。 My question is how to format the additional hover data to 2 decimal place?我的问题是如何将附加的 hover 数据格式化为小数点后 2 位?

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:如果你是那种喜欢 lambda 函数的 pythonista ,你也可以使用 go :

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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