【问题标题】:Plotly: Display date in specified format in hoverlabel (customdata reading date as string)Plotly:在 hoverlabel 中以指定格式显示日期(customdata 将日期读取为字符串)
【发布时间】:2021-06-14 10:50:34
【问题描述】:
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()

运行此代码会给出此悬停标签输出-

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

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

【问题讨论】:

    标签: python formatting plotly data-visualization plotly-python


    【解决方案1】:

    事实证明,plotly.express 中的 custom_datagraph_objects 中的 customdata 并不完全可以互换。解决方案是从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:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-16
      • 2018-08-30
      • 2013-12-28
      • 2022-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-12
      相关资源
      最近更新 更多