如何在Plotly中设置自定义xticks?

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

来自plotly doc:

enter image description here

示例:

import pandas as pd
import numpy as np

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


import plotly.graph_objects as go
import plotly.offline as py
import plotly.express as px
from plotly.offline import init_notebook_mode

init_notebook_mode(connected=True)


y = feature.set_index('ds').resample('D')['y'].sum()

fig = go.Figure()
fig.add_trace(go.Scatter(x=y.index, y=y))


x_dates = y.index.to_series().dt.strftime('%Y-%m-%d').sort_values().unique()


layout = dict(
    xaxis=dict(
        tickmode="array",
        tickvals=np.arange(0, x_dates.shape[0],2).astype(int),
        ticktext=x_dates[::2],
        tickformat='%Y-%m-%d',
        tickangle=45,
    )
)

fig.update_layout(layout)
fig.show()

结果:

enter image description here

由于x_dates[::2]的长度为50,所以报价号根本不匹配。我如何解决它?

python plotly plotly-python
1个回答
0
投票

没有正在运行的代码段和示例数据,给出合适的建议并不容易。但是对于在x轴上具有日期的类似情况,我通常使用这种方法:

代码段1:

fig.update_xaxes(tickangle=45,
                 tickmode = 'array',
                 tickvals = df_tips['date'][0::40],
                 ticktext= [d.strftime('%Y-%m-%d') for d in datelist])

图1:

enter image description here

现在您可以将tickvals = df_tips['date'][0::40]更改为tickvals = df_tips['date'][0::80]并获得:

图2:

enter image description here

完整代码:

import plotly.express as px
import pandas as pd
from datetime import datetime

df_tips = px.data.tips()
df_tips['date'] = df_tips.index
datelist = pd.date_range(datetime.today(), periods=df_tips.shape[0]).tolist()

fig = px.scatter(df_tips,x='date',y='tip', trendline='ols')
#fig = px.scatter(df_tips,x='date',y='tip', color = 'sex', trendline='ols')  

fig.update_xaxes(tickangle=45,
                 tickmode = 'array',
                 tickvals = df_tips['date'][0::80],
                 ticktext= [d.strftime('%Y-%m-%d') for d in datelist])

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