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

運行此代碼會給出此 hoverlabel 輸出 -

在此處輸入圖像描述

如您所見,日期顯示為長字符串。 如果我指定 d3 格式並將 hovertemplate 更改為'%{customdata|%d %b %Y}<br>%{y}' ,則 hoverlabel 看起來像這樣 -

在此處輸入圖像描述

我不知道如何解決它。 如果不是custom_data ,我以類似的方式使用參數text ,它會正確顯示日期。 但我已經在使用text在條形圖本身上顯示total_cases

事實證明, custom_dataplotly.expresscustomdatagraph_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM