Plotly。使用plotly express line时,如何在hoverinfo中格式化日期?

问题描述 投票:1回答:1

我使用下面的代码来显示时间序列数据,使用plotly express line。

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

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

python plotly data-visualization plotly-express
1个回答
1
投票

你可以通过正确组合 texthovertemplate 中。

for ser in fig['data']:
    ser['text']=list(set([d.strftime('%Y-%m-%d') for d in df['dates']]))
    ser['hovertemplate']='category=open<br>dates=%{text}<br>price=%{y}<extra></extra>'
fig.show()

ser['text']之所以这么乱,是因为结果显示的是 独一无二 在X轴上的日期。而且,由于 plotly.express 可在整洁或 长数据而非宽数据在你的数据集中,包含你的日期的那一列最可能是 具有唯一的日期值。

这里有一个例子,建立在一些不同类别的金融时间序列数据上,这是一个完美的案例。px.line:

enter image description here

有样本数据的完整代码。

# imports
import pandas as pd
import plotly.graph_objects as go
from datetime import datetime
import plotly.express as px

# data
open_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),
         datetime(year=2020, month=10, day=11),
         datetime(year=2020, month=10, day=12),
         datetime(year=2020, month=10, day=13),
         datetime(year=2020, month=10, day=14)]

# data organized in a pandas dataframe
df=pd.DataFrame(dict(open=open_data,
                    high=high_data,
                    low=low_data,
                    close=close_data,
                    dates=dates))

# transform the data from wide to long
df = pd.melt(df, id_vars=['dates'], value_vars=df.columns[:-1],
         var_name='category', value_name = 'price')

# setup for a perfect plotly time series figure
fig = px.line(df, x="dates", y="price", title='Prices', color = 'category')

# edit text and hovertemplate
for ser in fig['data']:
    ser['text']=list(set([d.strftime('%Y-%m-%d') for d in df['dates']]))
    ser['hovertemplate']='category=open<br>dates=%{text}<br>price=%{y}<extra></extra>'

fig.show()
© www.soinside.com 2019 - 2024. All rights reserved.