簡體   English   中英

Plotly:如何沿 x 軸更改時間分辨率?

[英]Plotly: How to change the time resolution along the x-axis?

我想繪制一些時間序列數據,其中數據的歷史部分具有每日分辨率,而當天的數據具有分鍾分辨率。 有沒有辦法以某種方式“拆分” x 軸,以便對於歷史數據它只顯示日期,而對於當前數據它也顯示時間?

目前它看起來像這樣,它並不是那么可讀

在此處輸入圖片說明

我認為唯一可行的方法是將兩個子圖放在一起。 但是使用正確的設置應該可以使子圖達到您所描述的幾乎 100%。 您只需要調整一些細節,例如:

fig = make_subplots(rows=1, cols=2,
                    horizontal_spacing = 0,
                    shared_yaxes=True,
                    shared_xaxes=True)

在此處輸入圖片說明

完整代碼:

# import pandas as pd
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from plotly.subplots import make_subplots
import plotly.graph_objects as go

# custom function to set the first
# minute dataset to contiunue from
# the last day in the day dataset
def next_day(date):
    s = date
    date = datetime.strptime(s, "%Y-%m-%d")
    next_date = date + timedelta(days=1)
    return(datetime.strftime(next_date, "%Y-%m-%d"))

# data
np.random.seed(10)
n_days = 5
n_minutes = (2*24)
dfd = pd.DataFrame({'time':[t for t in pd.date_range('2020', freq='D', periods=n_days).format()],
                      'y':np.random.uniform(low=-1, high=1, size=n_days).tolist()})

dfm = pd.DataFrame({'time':[t for t in pd.date_range(next_day(dfd['time'].iloc[-1]), freq='min', periods=n_minutes).format()],
                      'y':np.random.uniform(low=-1, high=1, size=n_minutes).tolist()})
dfm['y'] = dfm['y'].cumsum()

# subplot setup
fig = make_subplots(rows=1, cols=2,
                    horizontal_spacing = 0,
                    shared_yaxes=True,
                    shared_xaxes=True)

# trace for days
fig.add_trace(
    go.Scatter(x=dfd['time'], y=dfd['y'], name = 'days'),
    row=1, col=1
)

# trace for minutes
fig.add_trace(
    go.Scatter(x=dfm['time'], y=dfm['y'], name = 'minutes'),
    row=1, col=2
)

# some x-axis aesthetics
fig.update_layout(xaxis1 = dict(tickangle=0))
fig.update_layout(xaxis2 = dict(tickangle=90))
fig.add_shape( dict(type="line",
                    x0=dfd['time'].iloc[-1],
                    y0=dfd['y'].iloc[-1],
                    x1=dfm['time'].iloc[0],
                    y1=dfm['y'].iloc[0],
                    xanchor = 'middle',
                    xref = 'x1',
                    yref = 'y1',
                    line=dict(dash = 'dash',
                              color="rgba(0,0,255,0.9)",
                              width=1
            )))

fig.update_xaxes(showgrid=False)
fig.update_layout(template = 'plotly_dark')

fig.show()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM