我通常使用下面的方法。你应该知道tickvals
被视为位置性的参数并且对于数值而非日期效果最好(也许仅)。使用ticktext
以您喜欢的格式显示日期。
片段 1:
fig.update_xaxes(tickangle=45,
tickmode = 'array',
tickvals = df_tips['date'][0::40],
ticktext= [d.strftime('%Y-%m-%d') for d in datelist])
Plot 1:
现在你可以改变tickvals=np.arange(0, y.shape[0]).astype(int)[0::40]
to tickvals=np.arange(0, y.shape[0]).astype(int)[0::80]
并得到:
Plot 2:
那为什么第一次这对你不起作用呢?有几个原因:
- 您的重新采样熊猫系列 y有日期作为索引,所以
y.index
被设置为 x 轴值。
-
y.index
回报dates
- 当您设置刻度线时职位通过
fig.update_xaxes(tickvals)
,这可以更好地与integer values.
我做了什么来解决这个问题?
- 我在重新采样后重置索引,以便
y.index
不返回日期。
- 使用将 y 更改为数据框
.to_frame
.
- 变成
fig.add_trace(go.Scatter(x=y.index, y=y.y))
否则将会失败,因为这现在是一个数据框而不是一个系列。
- 您的日期现在检索为
x_dates = y.ds
I know y=y.y
looks really很奇怪,但我只是这样保留它作为一个友好的提醒,给你的 pandas 系列或数据框提供比单个字母更明智的名称,例如y
这更容易与单个、无索引、数组或列表混淆。
完整代码:
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import plotly.offline as py
import plotly.express as px
from plotly.offline import init_notebook_mode
# data
np.random.seed(42)
feature = pd.DataFrame({'ds': pd.date_range('20200101', periods=100*24, freq='H'),
'y': np.random.randint(0,20, 100*24) ,
'yhat': np.random.randint(0,20, 100*24) ,
'price': np.random.choice([6600, 7000, 5500, 7800], 100*24)})
# resampling
y = feature.set_index('ds').resample('D')['y'].sum()#.to_frame()
y=y.to_frame()
y.reset_index(inplace=True)
# plotly setup
fig = go.Figure()
fig.add_trace(go.Scatter(x=y.index, y=y.y))
# x-ticks preparations
x_dates = y.ds
tickvals=np.arange(0, y.shape[0]).astype(int)[0::40]
ticktext=x_dates
# update tickmarks
fig.update_xaxes(tickangle=45,
tickmode = 'array',
tickvals = tickvals,
ticktext=[d.strftime('%Y-%m-%d') for d in ticktext])
fig.show()