python - 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
条形图本身。
解决方案
事实证明,custom_data
ofplotly.express
和customdata
ofgraph_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:
)
推荐阅读
- reactjs - react 是否有机制在不同的 dom 级别移动子级,例如 Flutter 中 GlobalKey 的功能
- c - 我的转化价值是否正确?十六进制字符串到字节数组
- jasper-reports - 使用 ArrayList 创建子报表,其中包含 ArrayLists 作为 DataSource(JasperReports 社区)
- python - 将 4 维张量转换为列表列表(Python)
- apache - 将 .c 文件中的所有内容导出到 .so apache 模块
- c# - 在 Calli 指令中使用 Reflection.Emit 生成 modopt
- electron - Electron js - 安装问题
- javascript - 我可以在弹出窗口中打开一些重力场吗?
- javascript - org.apache.tiles.util.TilesIOException:JSPException 包括路径
- angular - 嵌套的可观察对象在终止后一个接一个地执行