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

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

运行 此代码给出了此 hoverlabel 输出-

如您所见,日期显示为一长串。如果我指定 d3 格式并将 hovertemplate 更改为 '%{customdata|%d %b %Y}<br>%{y}',则 hoverlabel 看起来像这样-

我不确定如何修复它。如果我以类似的方式使用参数 text 而不是 custom_data,它会正确显示日期。但我已经在使用 text 在条形图本身上显示 total_cases

事实证明,plotly.expresscustom_datagraph_objectscustomdata 不能完全互换。解决方案是从 px 调用中删除 custom_data,而是将 customdata 添加到跟踪调用中。这是完整的代码-

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

编辑:

该解决方案适用于静态日期,但如果要在每一帧中更新日期,则它们必须在列表中,并且该列表可以通过现有循环遍历 (for frame in fig.frames:)