python - Plotly:如何设置自定义 xticks

标签 python plotly plotly-python

来自 plotly doc :

layout > xaxis > tickvals:

Sets the values at which ticks on this axis appear. Only has an effect if tickmode is set to "array". Used with ticktext.

layout > xaxis > ticktext:

Sets the text displayed at the ticks position via tickvals. Only has an effect if tickmode is set to "array". Used with tickvals.



例子:

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 ,ticknumber 根本不匹配。
我如何解决它?

最佳答案

我通常使用下面的方法。你应该知道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])

图 1:

enter image description here

现在您可以更改 tickvals=np.arange(0, y.shape[0]).astype(int)[0::40]tickvals=np.arange(0, y.shape[0]).astype(int)[0::80]并得到:

plotly 2:

plot2

那么为什么这第一次对你不起作用呢?几个原因:
  • 您重新采样的 Pandas 系列 y 有日期作为索引,所以 y.index被设置为 x 轴值。
  • y.index返回日期
  • 当您通过 fig.update_xaxes(tickvals) 设置刻度线位置时,这对整数值效果更好。

  • 我做了什么来修复它?
  • 我在重采样后重置索引,以便 y.index不返回日期。
  • 使用 .to_frame 将 y 更改为数据框.
  • 改为 fig.add_trace(go.Scatter(x=y.index, y=y.y))否则会失败,因为这现在是一个数据框而不是一个系列。
  • 您的日期现在检索为 x_dates = y.ds

  • 我知道 y=y.y看起来真的很奇怪,但我只是把它留下来作为一个友好的提醒,给你的 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()
    

    关于python - Plotly:如何设置自定义 xticks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61861739/

    相关文章:

    python - Webkit2png 不适用于 --ignore-ssl-check

    python - Numpy 大小要求

    python - 如何使用python绘制彼此相邻的绘图仪表图?

    python - 使用 plotly.express 折线图,线条以奇怪的顺序连接?怎么修?

    python - 使用 Pandas Dataframe 和 Plotly 绘制包含 2 个数据系列的条形图

    python - obj.split() 和 obj 之间的区别

    python - 两个巨大稠密矩阵的乘法 Hadamard-乘以一个稀疏矩阵

    python - Plotly xlabel 和 ylabel 名称被裁剪如何使它们显得完整?

    python - 是否有任何函数可以使用Python在Plotly中绘制类似于geom_smooth()的函数?

    python - 将水平线添加到 Dash-Plotly Python 仪表板