I am trying to plot 2 different variables from a dataframe that is being updated in a 2 different graph with different intervals. I am having several problems because at some point one of the line of one graph disappear and starts plotting the same variables that is being plot in the other graph.
df=pd.DataFrame()
df['patient']= [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4]
df['heart rate']=np.random.uniform(low=50, high=100, size=80)
df['respiratory rate']=np.random.uniform(low=20,high=70, size=80)
df['temperature']=np.random.uniform(low=35.7,high=40, size=80)
df['oxygen saturation']=np.random.uniform(low=80,high=100,size=80)
df['physiology']=[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
df['systolic blood pressure']=np.random.uniform(low=55,high=120,size=80)
df['diastolic blood pressure']=np.random.uniform(low=30, high=95,size=80)
df['bedID']= [6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7]
df['age']=[12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
df['score']=""
rng = pd.date_range('2015-02-24', periods=80, freq='h')
df['datetime']=rng
patient_id=pd.unique(df['patient'])
def nuevoRegistro(df, paciente):
# Los datos que no van a variar y no hace falta simular se obtienen del ultimo registro del paciente
physiology = df.loc[df['patient']==paciente]['physiology'].values[-1]
bedID = df.loc[df['patient']==paciente]['bedID'].values[-1]
age = df.loc[df['patient']==paciente]['age'].values[-1]
# Este bloque te lo copio de arriba para que sea igual que los datos que tienes
HR = np.random.uniform(low=50, high=100, size=1)
RR = np.random.uniform(low=20,high=70, size=1)
Temp = np.random.uniform(low=35.7,high=40, size=1)
OxS = np.random.uniform(low=80,high=100,size=1)
SBP = np.random.uniform(low=55,high=120,size=1)
DBP = np.random.uniform(low=30, high=95,size=1)
# Este igual debería calcularlo pero nose ni lo que es, asique solo como prueba, asi se queda
score = Calculate_Score(age, physiology, HR, OxS, RR, Temp, SBP, DBP)
# print(score[0])
# SpO2, HR, RR, temp, SBP,DBP
# Para la hora voy a suponer que es en intervalos de una hora, asique cojo el anterior registro y le sumo 1
datetime = df.loc[df['patient']==paciente]['datetime'].values[-1] + pd.Timedelta(1, 'h')
df_aux = pd.DataFrame([[paciente, HR[0], RR[0],Temp[0], OxS[0], physiology, SBP[0], DBP[0], bedID, age, score[0], datetime,
score[1], score[2],score[3],score[4],score[5],score[6]
]],
columns= df.columns
)
# Ojo con esto, que el append en pandas es un concat: no añade una fila, devuelve un objeto nuevo, es costoso
# tenlo en cuenta por si los dataframes van a ser muy grandes, que entonces se petará
df = df.append(df_aux, ignore_index=True)
return df
def graph_principal(out,imp,patient,interval,typ):
# global df
# df=nuevoRegistro(df,patient)
@app.callback(
Output(str(out),'figure'),
[Input(str(imp),'value'),
Input(str(interval),'n_intervals'),
])
def graph_dynamic(variables8,interval):
if variables8 is None:
raise dash.exceptions.PreventUpdate()
else:
global df
if type(variables8)==str:
variables8=[variables8]
else:
variables8=variables8
traces=[]
y={'score':'y1','heart rate':'y1','respiratory rate':'y1', 'oxygen saturation':'y2',
'systolic blood pressure':'y1', 'diastolic blood pressure':'y2', 'score_HR':'y2',
'score_spO2':'y2', 'score_RR':'y1', 'score_temp':'y2','score_SBP':'y1','score_DBP':'y1'}
var=[]
var.append(str(variables8))
df=nuevoRegistro(df,patient)
for data in variables8:
print(var)
f.extend(df.loc[df['patient']==patient][data]) #extend
g.extend(df.sort_values(by='datetime', ascending=True).query('patient=='+str(patient))['datetime'])
traces.append(go.Scatter(x=list(g), y=list(f),mode='lines+markers', name=str(data),
line=dict(color=d[str(data)], width=3),yaxis=y[data]))
if len(var[0])>1:
layout=go.Layout(xaxis=dict(range=[min(g),max(g)]),yaxis=dict(title=str(var[0][1])),
yaxis2=dict(title=str(var[0][1]),overlaying='y',position=1,side='right')
)
fig=go.Figure(data=traces, layout=layout)
fig.update_layout(
yaxis=dict(showgrid=False),xaxis=dict(showgrid=False),dragmode='pan',clickmode='select',hovermode="x unified",
hoverlabel=dict(bgcolor='#00FFFF', bordercolor='#00FFFF'), margin=dict( l=20, r=20, b=20, t=20, pad=5 ),
legend=dict(orientation="h",y=1.0),
paper_bgcolor='#483D8B' ,font_color="white",plot_bgcolor='#483D8B')
fig.update_xaxes(title_text='Time' )
# rangeslider_visible=True,rangeslider_thickness=0.2, rangeslider_range=[str(df.loc[df['patient']==patient]['datetime'].iloc[0]),str(df.loc[df['patient']==patient]['datetime'].iloc[-1])]
fig.add_hline(y=50, line_width=3, line_dash="dash", line_color="black")
# fig.update_yaxes(title_text="Secondary yaxis title", secondary_y=True)
fig.update_traces(showlegend=True)
else:
layout=go.Layout(xaxis=dict(range=[min(g),max(g)]), yaxis=dict(title=str(var)),
yaxis2=dict(overlaying='y',position=1,side='right',title=str(var)))
fig=go.Figure(data=traces, layout=layout)
fig.update_layout(yaxis=dict(showgrid=False),xaxis=dict(showgrid=False),dragmode='pan',clickmode='select',hovermode="x unified",
hoverlabel=dict(bgcolor='#00FFFF', bordercolor='#00FFFF'), margin=dict( l=20, r=20, b=20, t=20, pad=5 ),
legend=dict(orientation="h",y=1.0),paper_bgcolor='#483D8B' ,font_color="white",plot_bgcolor='#483D8B')
fig.update_xaxes(title_text='Time' )
# rangeslider_visible=True,rangeslider_thickness=0.2, rangeslider_range=[str(df.loc[df['patient']==patient]['datetime'].iloc[0]),str(df.loc[df['patient']==patient]['datetime'].iloc[-1])]
fig.add_hline(y=50, line_width=3, line_dash="dash", line_color="black")
# fig.update_yaxes(title_text="Secondary yaxis title", secondary_y=True)
fig.update_traces(showlegend=True)
return fig
def tab(tab,drop, graph,interv, update):
r= dbc.Tab(tab_id=str(tab), label=str(tab), children=[
dbc.Container([
dbc.Row([
dbc.Col([
dbc.Card([dbc.CardBody([
dbc.Row([
dbc.Col([
html.Div([dropdown_scores(drop[0], True)], className='align-content-start')], className='align-content-start'),
#
], className='m-3',style=dict( display='flex'), no_gutters=True),
#First graph
dbc.Row([
dbc.Col([
dbc.Row([
dbc.Col([
dcc.Graph(id=str(graph[0]),animate=True,style={'width':'163vh', 'height':'45vh','display':'inline-block','line-height':'0px'}),
# hoverData={'points':[{'customdata':str(df.loc[df['patient']==1]['datetime'])}]}
]) ,
]), ], ),
], className="h-15",no_gutters=True),
dbc.Row([
dbc.Col([
html.Div([dropdown_hr_spo2(drop[1], True)], className='align-content-start', style={'marginBottom': 0, 'marginTop':0})], className='align-content-start'),
#
], className='m-3',style=dict( display='flex'), no_gutters=True),
#Second graph
dbc.Row([
dbc.Col([
dbc.Row([
dbc.Col([
dcc.Graph(id=str(graph[1]),animate=True,style={'width':'163vh', 'height':'45vh','display':'inline-block','line-height':'0px'}), ]) ,
# dbc.Col([ dcc.Graph(id=graph[1],style={'width':'81vh', 'height':'4', 'display':'inline-block'})])
]), ], ),
], className="h-15",no_gutters=True),
#Third graph
dbc.Row([
dbc.Col([
html.Div([
dropdown_bp(drop[2], True)
], className='align-content-start')], className='align-content-start'),
# dbc.Col([
# html.Div([
# dropdown(drop[3], False)
# ])], style={'size':6, 'offset':2})
], className='m-3',style=dict( display='flex'),no_gutters=True),
#Fourth graph
dbc.Row([
dbc.Col([dcc.Graph(id=str(graph[2]),style={'width':'165vh', 'height':'45vh', 'display':'inline-block','line-height':'40px'}) ]),
# dbc.Col([ dcc.Graph(id=str(graph[3]),style={'width':'81vh', 'height':'4', 'display':'inline-block', 'scrollZoom':True})
],no_gutters=True)
]),
dbc.Row([ dbc.Col([
dcc.Interval(id=str(interv[0]
),interval=1*5000,n_intervals=0),
html.Div([dropdown_rr(drop[3],True) ], className='align-content-start')], className='align-content-start')]
,className='m-3',style=dict( display='flex'),no_gutters=True
# style={'size':6, 'offset':2}
),
# dbc.Col([
# html.Div([
# # dropdown(drop[5],True)
# ])
# ])
#Fourth graph
dbc.Row([
# dbc.Col([dcc.Graph(id= str(graph[4]), style={'width':'81vh', 'height':'4', 'display':'inline-block','line-height':'40px'})], ),
dbc.Col([
# html.Div([html.Div(id=str(update),children=[]),
dcc.Interval(id=str(interv[1]
),interval=1*5000,n_intervals=0),
dcc.Graph(id=graph[3],style={'width':'165vh', 'height':'45vh','display':'inline-block','line-height':'40px'} )
])
],no_gutters=True),
#Fourth graph
# dbc.Row([
# # dbc.Col([dcc.Graph(id= str(graph[4]), style={'width':'81vh', 'height':'4', 'display':'inline-block','line-height':'40px'})], ),
# dbc.Col([
# # html.Div([html.Div(id=str(update),children=[]),
# # dcc.Interval(id=str(interv[1]
# # ),interval=1*5000,n_intervals=0),
# dcc.Graph(figure=lc,style={'width':'165vh', 'height':'45vh','display':'inline-block','line-height':'40px'} )
# ])
# ],no_gutters=True),
])
, ], style={'backgroundColor':'#9932CC', "height":"100rem"} )
]),
],fluid=True, style={'backgroundColor':'#483D8B'}),
])
return r