![](/img/trans.png)
[英]Plotly-Dash: How to update only figure data without changing the figure layout?
[英]Plotly: How to show only today's data on a figure?
我在 X 軸上使用時間軸制作了一個圖表,但是我只想顯示今天的數據。 (即限制日期為當前日期)
這是我用來生成這些圖表的代碼:
fig = go.Figure()
fig = make_subplots(rows=2,cols=1,shared_xaxes=True,vertical_spacing=0.02)
fig.add_trace(go.Scatter(x=data['time'],y=data['x_last_recorded'],name='xyz',mode='lines+markers'),row=2,col=1)
fig.add_trace(go.Scatter(x=predict_data['time'],y=predict_data['x1_last_recorded'],name='x1yz',mode='lines'),row=2,col=1)
fig.update_layout(height=800,width=1500,title='first_graph',yaxis_title='Values')
這給了我一張我想要的圖表,但它顯示了 dataframe 中存在的所有日期。 如何僅獲取當前日期的數據? 時間結構:dd-mm-yyyy hh:mm
我們可以通過使用諸如df_current = df[df.index.date==df.index.date[-1]]
類的方法對您的 dataframe 進行子集化來解決您的挑戰,然后通過讓不同的子集由不同的選項表示來重新設置您的圖形在下拉菜單中。
這是不同子集/選擇選項的結果圖:
# imports
import plotly.graph_objects as go
import pandas as pd
import numpy as np
# sample data in the form of an hourlt
np.random.seed(1234)
tseries = pd.date_range("01.01.2020", "01.04.2020", freq="H")
data = np.random.randint(-10, 12, size=(len(tseries), 2))
df = pd.DataFrame(index=tseries, data=data)
df.drop(df.tail(1).index,inplace=True)
df.columns=list('AB')
df.iloc[0]=0
df=df.cumsum()
# subset method
df_current = df[df.index.date==df.index.date[-1]]
# plotly setup
fig = go.Figure()
# set up a trace for each column in a dataframe
for col in df.columns:
fig.add_trace(go.Scatter(x=df.index, y =df[col], name=col))
# container for updatemenus and buttons
updatemenu = []
buttons = []
# button 1
buttons.append(dict(method='restyle',
label='All',
visible=True,
args=[{'y':[df[col].values for col in df.columns],
'x':[df.index],
'type':'scatter'}, ],))
# button 2
buttons.append(dict(method='restyle',
label='Current',
visible=True,
args=[{'y':[df_current[col].values for col in df_current.columns],
'x':[df_current.index],
'type':'scatter'}, ],))
# menu setup
your_menu = dict()
updatemenu.append(your_menu)
updatemenu.append(your_menu)
updatemenu[0]['buttons'] = buttons
updatemenu[0]['direction'] = 'down'
updatemenu[0]['showactive'] = True
# add dropdown menus to the figure
fig.update_layout(showlegend=False, updatemenus=updatemenu)
fig.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.