sustitución gráficas 'características de la pob' y 'dist población'

estas gráficas mostraban un scatter y un hist de algunas de las
mediciones
que se hacen a la población. casi todas eran QS -con adición de IMC-

ahora, se puso un selector que permite al usuario escoger el grupo de
variables que quiere visualizar. además, un selector adicional permite
escoger entre ver a toda la población junta o una separación de M/F.

la población junta muestra el scatter + la distribución de cada
variable. la población separada solo muestra el scatter para cada
grupo poblacional.

en cada grupo de variables, es posible definir una lista de las
variables que no se van a mostar. Pej, 'glucagon' en las de QS.
parent 8a8851af
...@@ -16,50 +16,6 @@ server = flask.Flask(__name__) ...@@ -16,50 +16,6 @@ server = flask.Flask(__name__)
def datavis(datos):
medidas = ["imc", "age", "glucose", "hba1c", "ct", "hdl"]
fig = make_subplots(rows=2, cols=3, vertical_spacing=0.25)
lcol = 1
lrow = 1
seq = 1
for medida in medidas:
fig.add_trace(
go.Scatter(x=datos["id"], y=datos[medida], name=medida,mode="markers"),
row=lrow, col=lcol
)
fig['layout']['xaxis' + str(seq)]['title']='Patient ID'
fig['layout']['yaxis' + str(seq)]['title']=medida
seq = seq + 1
lrow = lrow + (lcol // 3)
lcol = lcol + 1 if lcol < 3 else 1
fig.update_layout(showlegend = False)
return fig
def popdist(datos):
medidas = ["imc", "age", "glucose", "hba1c", "ct", "hdl"]
# remoemos outliers
fig = make_subplots(rows=2, cols=3, vertical_spacing = 0.25 )
lcol = 1
lrow = 1
seq = 1
for medida in medidas:
datosfil = datos[np.abs(stats.zscore(datos[medida], nan_policy='omit')) < 3]
fig.add_trace(
go.Histogram(x=datosfil[medida], name=medida),
row=lrow, col=lcol
)
fig['layout']['yaxis' + str(seq)]['title']=medida
seq = seq + 1
lrow = lrow + (lcol // 3)
lcol = lcol + 1 if lcol < 3 else 1
fig.update_layout(
bargap=0.05, # gap between bars of adjacent location coordinates
bargroupgap=0.05, # gap between bars of the same location coordinates
showlegend = False
)
return fig
def popcorr(datos): def popcorr(datos):
medidas = [ "glucose", "hba1c", "ct", "hdl", "insuline"] medidas = [ "glucose", "hba1c", "ct", "hdl", "insuline"]
...@@ -266,7 +222,7 @@ def get_visit_data(visitnumber): ...@@ -266,7 +222,7 @@ def get_visit_data(visitnumber):
df = pd.json_normalize(yaisons) df = pd.json_normalize(yaisons)
df.drop(["tolerance_curve_measure","name","patient_visit_id", "visit_date"], inplace=True, axis=1) df.drop(["tolerance_curve_measure","name","patient_visit_id", "visit_date"], inplace=True, axis=1)
lista = [ { cf["controlled_food"]: cf["increment_auc"] for cf in yaison["tolerance_curve_measure"] } for yaison in yaisons ] lista = [ { cf["controlled_food"]: cf["increment_auc"] for cf in yaison["tolerance_curve_measure"] } for yaison in yaisons ]
df.rename(columns= lambda x: x.split(".")[1] if "." in x else x, inplace=True) #df.rename(columns= lambda x: x.split(".")[1] if "." in x else x, inplace=True)
#df.drop(["patient_visit_id"], inplace=True, axis=0) #esta etiqueta aparece dos veces: dentro del primer nivel de json y dentro del json de sample #df.drop(["patient_visit_id"], inplace=True, axis=0) #esta etiqueta aparece dos veces: dentro del primer nivel de json y dentro del json de sample
return pd.concat([df, pd.DataFrame(lista)], axis=1) return pd.concat([df, pd.DataFrame(lista)], axis=1)
...@@ -276,6 +232,8 @@ def get_visit_data(visitnumber): ...@@ -276,6 +232,8 @@ def get_visit_data(visitnumber):
# visitas y microbiota # visitas y microbiota
visitas_datos = [ get_visit_data(visita) for visita in range(1, 5)] visitas_datos = [ get_visit_data(visita) for visita in range(1, 5)]
visitas_incluidos = visitas_datos[0].loc[visitas_datos[0]["include_in_analysis"]] visitas_incluidos = visitas_datos[0].loc[visitas_datos[0]["include_in_analysis"]]
visitas_test = visitas_incluidos.copy()
visitas_incluidos.rename(columns= lambda x: x.split(".")[1] if "." in x else x, inplace=True)
external_stylesheets = [ external_stylesheets = [
{ {
"href": ( "href": (
...@@ -301,14 +259,21 @@ app.layout = html.Div(children=[ ...@@ -301,14 +259,21 @@ app.layout = html.Div(children=[
# descripción por diferentes indices # descripción por diferentes indices
html.Div(children=[ html.Div(children=[
html.Div(children= [ html.H1("Características de la población", className= "header-title2"),], ), html.Div(children= [ html.H1("Características de la población", className= "header-title2"),], ),
dcc.Graph(figure=datavis(visitas_incluidos)) dcc.Dropdown(
]), id="GrupoVar",
options=[
# descripción por diferentes indices {"label":"Biochemichal", "value":"biochemical_measure"},
html.Div(children=[ {"label":"Antroprometric", "value":"antropometric_measure"},
html.Div(children= [ html.H1("Distribuciones de la población", className= "header-title2"),], ), {"label":"Corporal Composition", "value":"corporal_composition"},
dcc.Graph(figure=popdist(visitas_incluidos)), {"label": "Physiological_measure", "value":"physiological_measure"}
],
value="biochemical_measure",
clearable=False,
searchable=False,
className="dropdown",
),
dcc.RadioItems(['Todos','Por Sexo'], 'Todos', inline=True, id="radio_desc"),
dcc.Graph(id='pobDesc')
]), ]),
# correlaciones entre indices de la poblacion # correlaciones entre indices de la poblacion
html.Div(children=[ html.Div(children=[
...@@ -416,6 +381,63 @@ def update_correlacion(controlado): ...@@ -416,6 +381,63 @@ def update_correlacion(controlado):
#figura.update_layout(height=600, width=800) #figura.update_layout(height=600, width=800)
return figura return figura
@callback(
Output("pobDesc", "figure"),
Input("radio_desc", "value"),
Input("GrupoVar", "value"),
)
def test(pob, grupo):
datos = visitas_test
# pob = "Por Sexo"
# pob = "Todos"
print(f"las columans son: {datos.columns}")
excluir = {'biochemical_measure': ['glucagon', 'glucagon_type'],
'antropometric_measure': [],
'corporal_composition': [],
'physiological_measure': ["ipaq","stress", "hadsa", "hadsd"]}
seccion = grupo
variables = datos.filter(regex=seccion, axis=1).columns.to_list()
print(f'variables is {type(variables)}')
variables.extend(["id", "sex"])
working_df = datos[variables]
working_df.rename(columns= lambda x: x.split(".")[1] if "." in x else x, inplace=True)
variables_plot = working_df.columns.to_list().remove("id")
print(f'ahora las columans son {working_df.columns}')
working_df.drop(excluir[seccion], axis=1, inplace=True)
working_df = working_df.melt(id_vars=["id","sex"], value_vars = variables_plot)
print(f'y las columnas ahora son {working_df.columns}')
print(f'los valores en variable son {working_df.head()}')
if pob == "Por Sexo":
fig = px.scatter(
working_df,
x='id',
y='value',
marginal_y = "histogram",
facet_row='variable',
facet_col="sex",
color='variable',
height=2000,
)
if pob == "Todos":
fig = px.scatter(
working_df,
x='id',
y='value',
facet_row='variable',
#facet_col_wrap=2,
marginal_y = "histogram",
color='variable',
height=2000,
)
fig.update_yaxes(showticklabels=True, matches=None)
# fig = px.scatter(working_df["hba1c"])
# fig.add_trace(px.scatter(working_df["glucose"]).data[0])
return fig
if __name__ == "__main__": if __name__ == "__main__":
app.run_server(debug=True, port=8052, host='0.0.0.0') app.run_server(debug=True, port=8052, host='0.0.0.0')
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment