简体   繁体   English

Plotly:在悬停标签中以指定格式显示日期(自定义数据读取日期为字符串)

[英]Plotly: Display date in specified format in hoverlabel (customdata reading date as string)

import pandas as pd
from pandas import Timestamp
import plotly.express as px

df = pd.DataFrame({'continent': {127: 'South America',
  128: 'South America'},
 'date': {127: Timestamp('2021-03-01 00:00:00'),
  128: Timestamp('2021-03-26 00:00:00')},
 'total_cases': {127: 20465329.0,
  128: 23470911.0}})

fig = px.bar(df, x='continent', y='total_cases', animation_frame=df.date.astype(str), text='total_cases',
            custom_data=['date'])

fig.update_traces(hovertemplate='%{customdata}<br>%{y}')
for frame in fig.frames:
    frame.data[0].update(hovertemplate='%{customdata}<br>%{y}')
    
fig.show()

Running this code gives this hoverlabel output-运行此代码会给出此 hoverlabel 输出 -

在此处输入图像描述

As you can see, the date is displayed as a long string.如您所见,日期显示为长字符串。 If I specify the d3 format and change hovertemplate to '%{customdata|%d %b %Y}<br>%{y}' , the hoverlabel then looks like this-如果我指定 d3 格式并将 hovertemplate 更改为'%{customdata|%d %b %Y}<br>%{y}' ,则 hoverlabel 看起来像这样 -

在此处输入图像描述

I am not sure how to fix it.我不知道如何解决它。 If instead of custom_data , I use the argument text in a similar fashion, it displays the date correctly.如果不是custom_data ,我以类似的方式使用参数text ,它会正确显示日期。 But I am already using text to display total_cases on the bar chart itself.但我已经在使用text在条形图本身上显示total_cases

Turns out, custom_data of plotly.express and customdata of graph_objects are not exactly interchangeable.事实证明, custom_dataplotly.expresscustomdatagraph_objects不能完全互换。 The solution is to remove custom_data from the px call and rather adding customdata to the trace calls.解决方案是从px调用中删除custom_data ,而是将customdata添加到跟踪调用中。 Here is the complete code-这是完整的代码-

import pandas as pd
from pandas import Timestamp
import plotly.express as px

df = pd.DataFrame({'continent': {127: 'South America',
  128: 'South America'},
 'date': {127: Timestamp('2021-03-01 00:00:00'),
  128: Timestamp('2021-03-26 00:00:00')},
 'total_cases': {127: 20465329.0,
  128: 23470911.0}})

fig = px.bar(df, x='continent', y='total_cases', animation_frame=df.date.astype(str), text='total_cases')

fig.update_traces(customdata=df['date'], hovertemplate='%{customdata|%d %b %Y}<br>%{y}')
for frame in fig.frames:
    frame.data[0].update(hovertemplate='%{customdata|%d %b %Y}<br>%{y}')
    
fig.show()

在此处输入图像描述

Edit:编辑:

The solution will work for static dates but if the dates are to be updated in each frame, they have to be in a list and the list can be looped over by the existing loop ( for frame in fig.frames: )该解决方案适用于 static 日期,但如果要在每一帧中更新日期,它们必须在一个列表中,并且该列表可以由现有循环循环( for frame in fig.frames:

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

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