[英]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 看起來像這樣 -
我不知道如何解決它。 如果不是custom_data
,我以類似的方式使用參數text
,它會正確顯示日期。 但我已經在使用text
在條形圖本身上顯示total_cases
。
事實證明, custom_data
的plotly.express
和customdata
的graph_objects
不能完全互換。 解決方案是從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()
編輯:
該解決方案適用於 static 日期,但如果要在每一幀中更新日期,它們必須在一個列表中,並且該列表可以由現有循環循環( for frame in fig.frames:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.