Plotly:使用 plotly express 行时如何在 hoverinfo 中格式化日期?

我正在使用以下代码使用 plotly express 线显示时间序列数据。


fig = px.line(df, x="date", y="close", color="type" ,category_orders = co ,color_discrete_sequence = colors,

              line_group="type", title = company)


fig.update_layout(height=500, width=1500)#hovermode="x unified"

fig.show()

但是在悬停时的绘图中,它以以下格式显示日期:“月,年”,即它不显示日期。但我希望日期以以下格式显示:“月日,年”。


慕田峪4524236
浏览 203回答 1
1回答

慕哥6287543

text您可以通过和的正确组合来做到这一点hovertemplate:for ser in fig['data']:&nbsp; &nbsp; ser['text']=list(set([d.strftime('%Y-%m-%d') for d in df['dates']]))&nbsp; &nbsp; ser['hovertemplate']='category=open<br>dates=%{text}<br>price=%{y}<extra></extra>'fig.show()ser['text'] 之所以如此混乱,是因为结果图在 x 轴上显示了唯一的日期。而且,由于plotly.express适用于 tidy 或long 而不是 wide data,因此数据集中包含您的日期的列很可能没有唯一的日期值。这是一个基于一些具有不同类别的金融时间序列数据的示例,这是一个完美的案例px.line:带有示例数据的完整代码:# importsimport pandas as pdimport plotly.graph_objects as gofrom datetime import datetimeimport plotly.express as px# dataopen_data = [33.0, 33.3, 33.5, 33.0, 34.1]high_data = [33.1, 33.3, 33.6, 33.2, 34.8]low_data = [32.7, 32.7, 32.8, 32.6, 32.8]close_data = [33.0, 32.9, 33.3, 33.1, 33.1]dates = [datetime(year=2020, month=10, day=10),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;datetime(year=2020, month=10, day=11),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;datetime(year=2020, month=10, day=12),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;datetime(year=2020, month=10, day=13),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;datetime(year=2020, month=10, day=14)]# data organized in a pandas dataframedf=pd.DataFrame(dict(open=open_data,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; high=high_data,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; low=low_data,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; close=close_data,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dates=dates))# transform the data from wide to longdf = pd.melt(df, id_vars=['dates'], value_vars=df.columns[:-1],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var_name='category', value_name = 'price')# setup for a perfect plotly time series figurefig = px.line(df, x="dates", y="price", title='Prices', color = 'category')# edit text and hovertemplatefor ser in fig['data']:&nbsp; &nbsp; ser['text']=list(set([d.strftime('%Y-%m-%d') for d in df['dates']]))&nbsp; &nbsp; ser['hovertemplate']='category=open<br>dates=%{text}<br>price=%{y}<extra></extra>'fig.show()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python