File size: 7,997 Bytes
cbdab05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# app.py (Versi贸n 2.1 - Correcci贸n Final)

import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# --- 1. DICCIONARIO DE TEXTOS ---
# (Esta secci贸n no cambia)
TEXTS = {
    'es': {
        'page_title': "An谩lisis de Riesgo Cardiovascular", 'page_icon': "馃┖",
        'title': "Dashboard Interactivo de Factores de Riesgo Cardiovascular 馃┖",
        'lang_button': "English / Espa帽ol",
        'tab1': "馃敟 Correlaciones", 'tab2': "馃搳 An谩lisis Categ贸rico", 'tab3': "馃幓 An谩lisis Num茅rico",
        'corr_header': "Correlaci贸n entre Variables",
        'corr_desc': "Un mapa de calor para identificar r谩pidamente las relaciones lineales entre variables. Valores cercanos a +1 (rojo intenso) o -1 (azul intenso) indican una correlaci贸n fuerte.",
        'dict_header': "馃摉 Diccionario de Datos",
        'var_names': { 'age_years': "Edad (a帽os)", 'height': "Altura (cm)", 'weight': "Peso (kg)", 'bmi': "脥ndice de Masa Corporal (IMC)", 'ap_hi': "Presi贸n Arterial Sist贸lica", 'ap_lo': "Presi贸n Arterial Diast贸lica", 'cholesterol': "Nivel de Colesterol", 'gluc': "Nivel de Glucosa", 'smoke': "H谩bito de Fumar", 'alco': "H谩bito de Beber Alcohol", 'active': "Actividad F铆sica", 'cardio': "Presencia de Enfermedad Cardiovascular" },
        'cholesterol_labels': {1: 'Normal', 2: 'Elevado', 3: 'Muy Elevado'}, 'gluc_labels': {1: 'Normal', 2: 'Elevado', 3: 'Muy Elevado'},
        'binary_labels': {0: 'No', 1: 'S铆'}, 'cat_header': "An谩lisis Interactivo de Variables Categ贸ricas",
        'cat_desc': "Selecciona una variable para comparar la cantidad de pacientes (con y sin enfermedad) en cada categor铆a.",
        'cat_select': "Selecciona una variable categ贸rica:", 'cat_plot_title': "Distribuci贸n por Condici贸n Cardiovascular",
        'cat_axis_y': "Conteo de Pacientes", 'num_header': "An谩lisis Interactivo de Variables Num茅ricas",
        'num_desc': "Selecciona una variable para comparar su distribuci贸n (edad, peso, presi贸n arterial) entre pacientes sanos y enfermos.",
        'num_select': "Selecciona una variable num茅rica:", 'num_plot_title': "Distribuci贸n de {} por Condici贸n Cardiovascular",
        'legend_no_disease': "Sin Enfermedad", 'legend_with_disease': "Con Enfermedad",
    },
    'en': {
        'page_title': "Cardiovascular Risk Analysis", 'page_icon': "馃┖",
        'title': "Interactive Dashboard of Cardiovascular Risk Factors 馃┖",
        'lang_button': "Espa帽ol / English",
        'tab1': "馃敟 Correlations", 'tab2': "馃搳 Categorical Analysis", 'tab3': "馃幓 Numerical Analysis",
        'corr_header': "Correlation Between Variables",
        'corr_desc': "A heatmap to quickly identify linear relationships. Values close to +1 (deep red) or -1 (deep blue) indicate a strong correlation.",
        'dict_header': "馃摉 Data Dictionary",
        'var_names': { 'age_years': "Age (years)", 'height': "Height (cm)", 'weight': "Weight (kg)", 'bmi': "Body Mass Index (BMI)", 'ap_hi': "Systolic Blood Pressure", 'ap_lo': "Diastolic Blood Pressure", 'cholesterol': "Cholesterol Level", 'gluc': "Glucose Level", 'smoke': "Smoking Habit", 'alco': "Alcohol Intake", 'active': "Physical Activity", 'cardio': "Presence of Cardiovascular Disease" },
        'cholesterol_labels': {1: 'Normal', 2: 'Above Normal', 3: 'Well Above Normal'}, 'gluc_labels': {1: 'Normal', 2: 'Above Normal', 3: 'Well Above Normal'},
        'binary_labels': {0: 'No', 1: 'Yes'}, 'cat_header': "Interactive Analysis of Categorical Variables",
        'cat_desc': "Select a variable to compare the number of patients (with and without disease) in each category.",
        'cat_select': "Select a categorical variable:", 'cat_plot_title': "Distribution by Cardiovascular Condition",
        'cat_axis_y': "Patient Count", 'num_header': "Interactive Analysis of Numerical Variables",
        'num_desc': "Select a variable to compare its distribution (age, weight, blood pressure) between healthy and sick patients.",
        'num_select': "Select a numerical variable:", 'num_plot_title': "Distribution of {} by Cardiovascular Condition",
        'legend_no_disease': "No Disease", 'legend_with_disease': "With Disease",
    }
}

# --- L脫GICA DE LA APP (Sin cambios) ---
if 'lang' not in st.session_state:
    st.session_state.lang = 'en'
def toggle_language():
    st.session_state.lang = 'es' if st.session_state.lang == 'en' else 'en'
st.set_page_config(page_title=TEXTS[st.session_state.get('lang', 'en')]['page_title'], page_icon="馃┖", layout="wide")
texts = TEXTS[st.session_state.lang]

@st.cache_data
def load_data():
    df = pd.read_csv('cardio_train.csv', sep=';')
    df['age_years'] = (df['age'] / 365.25).round().astype(int)
    df = df[(df['ap_hi'] >= 90) & (df['ap_hi'] <= 240) & (df['ap_lo'] >= 60) & (df['ap_lo'] <= 140)]
    df.drop(columns=['id', 'age'], inplace=True)
    return df
df = load_data()

# --- INTERFAZ ---
st.button(texts['lang_button'], on_click=toggle_language)
st.title(texts['title'])

tab_keys = ['tab1', 'tab2', 'tab3']
tab_labels = [texts[key] for key in tab_keys]
tab1, tab2, tab3 = st.tabs(tab_labels)

with tab1:
    # (El c贸digo de la Tab 1 no cambia)
    st.header(texts['corr_header']); st.write(texts['corr_desc'])
    correlation_matrix = df.corr()
    fig, ax = plt.subplots(figsize=(14, 10))
    sns.heatmap(correlation_matrix, annot=True, fmt='.2f', cmap='coolwarm', ax=ax)
    st.pyplot(fig)
    with st.expander(texts['dict_header']):
        for var, desc in texts['var_names'].items(): st.markdown(f"**{var}:** {desc}")

with tab2:
    # (El c贸digo de la Tab 2 no cambia)
    st.header(texts['cat_header']); st.write(texts['cat_desc'])
    cat_vars_keys = ['cholesterol', 'gluc', 'smoke', 'alco', 'active']
    selected_cat_var = st.selectbox(texts['cat_select'], options=cat_vars_keys, format_func=lambda var: texts['var_names'][var])
    if selected_cat_var:
        fig, ax = plt.subplots(figsize=(10, 6))
        sns.countplot(x=selected_cat_var, hue='cardio', data=df, ax=ax, palette='pastel')
        ax.set_title(f"{texts['var_names'][selected_cat_var]}", fontsize=16)
        ax.set_xlabel(texts['var_names'][selected_cat_var], fontsize=12)
        ax.set_ylabel(texts['cat_axis_y'], fontsize=12)
        if selected_cat_var == 'cholesterol': ax.set_xticklabels([texts['cholesterol_labels'][i] for i in sorted(df[selected_cat_var].unique())])
        elif selected_cat_var == 'gluc': ax.set_xticklabels([texts['gluc_labels'][i] for i in sorted(df[selected_cat_var].unique())])
        else: ax.set_xticklabels([texts['binary_labels'][i] for i in sorted(df[selected_cat_var].unique())])
        handles, _ = ax.get_legend_handles_labels(); ax.legend(handles, [texts['legend_no_disease'], texts['legend_with_disease']], title='Condici贸n')
        st.pyplot(fig)

with tab3:
    st.header(texts['num_header'])
    st.write(texts['num_desc'])

    num_vars_keys = ['age_years', 'height', 'weight', 'ap_hi', 'ap_lo']
    selected_num_var = st.selectbox(texts['num_select'], options=num_vars_keys, format_func=lambda var: texts['var_names'][var])

    if selected_num_var:
        fig, ax = plt.subplots(figsize=(10, 6))
        sns.violinplot(x='cardio', y=selected_num_var, data=df, ax=ax, palette='pastel')
        
        # --- INICIO DE LA CORRECCI脫N ---
        # Simplificamos la creaci贸n del t铆tulo para evitar errores
        title_template = texts['num_plot_title']
        variable_name = texts['var_names'][selected_num_var]
        final_title = title_template.format(variable_name)
        ax.set_title(final_title, fontsize=14)
        # --- FIN DE LA CORRECCI脫N ---
        
        ax.set_xticklabels([texts['legend_no_disease'], texts['legend_with_disease']])
        ax.set_xlabel(None)
        ax.set_ylabel(texts['var_names'][selected_num_var], fontsize=12)
        st.pyplot(fig)