首页 > 解决方案 > Plotly:在 hoverlabel 中以指定格式显示日期(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',
            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 看起来像这样-

在此处输入图像描述

我不知道如何解决它。如果不是custom_data,我text以类似的方式使用参数,它会正确显示日期。但我已经用text它来显示total_cases条形图本身。

标签: pythonformattingplotlydata-visualizationplotly-python

解决方案


事实证明,custom_dataofplotly.expresscustomdataofgraph_objects并不完全可以互换。custom_data解决方案是从调用中删除,px而不是添加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:)


推荐阅读