dezzKnown commited on
Commit
cbdab05
路
verified 路
1 Parent(s): 44b8b2a

1st commit on Cardio Analysis

Browse files
Files changed (4) hide show
  1. .gitignore +1 -0
  2. app.py +124 -0
  3. cardio_train.csv +0 -0
  4. requirements.txt +5 -3
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ cardio_train.csv
app.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py (Versi贸n 2.1 - Correcci贸n Final)
2
+
3
+ import streamlit as st
4
+ import pandas as pd
5
+ import numpy as np
6
+ import matplotlib.pyplot as plt
7
+ import seaborn as sns
8
+
9
+ # --- 1. DICCIONARIO DE TEXTOS ---
10
+ # (Esta secci贸n no cambia)
11
+ TEXTS = {
12
+ 'es': {
13
+ 'page_title': "An谩lisis de Riesgo Cardiovascular", 'page_icon': "馃┖",
14
+ 'title': "Dashboard Interactivo de Factores de Riesgo Cardiovascular 馃┖",
15
+ 'lang_button': "English / Espa帽ol",
16
+ 'tab1': "馃敟 Correlaciones", 'tab2': "馃搳 An谩lisis Categ贸rico", 'tab3': "馃幓 An谩lisis Num茅rico",
17
+ 'corr_header': "Correlaci贸n entre Variables",
18
+ '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.",
19
+ 'dict_header': "馃摉 Diccionario de Datos",
20
+ '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" },
21
+ 'cholesterol_labels': {1: 'Normal', 2: 'Elevado', 3: 'Muy Elevado'}, 'gluc_labels': {1: 'Normal', 2: 'Elevado', 3: 'Muy Elevado'},
22
+ 'binary_labels': {0: 'No', 1: 'S铆'}, 'cat_header': "An谩lisis Interactivo de Variables Categ贸ricas",
23
+ 'cat_desc': "Selecciona una variable para comparar la cantidad de pacientes (con y sin enfermedad) en cada categor铆a.",
24
+ 'cat_select': "Selecciona una variable categ贸rica:", 'cat_plot_title': "Distribuci贸n por Condici贸n Cardiovascular",
25
+ 'cat_axis_y': "Conteo de Pacientes", 'num_header': "An谩lisis Interactivo de Variables Num茅ricas",
26
+ 'num_desc': "Selecciona una variable para comparar su distribuci贸n (edad, peso, presi贸n arterial) entre pacientes sanos y enfermos.",
27
+ 'num_select': "Selecciona una variable num茅rica:", 'num_plot_title': "Distribuci贸n de {} por Condici贸n Cardiovascular",
28
+ 'legend_no_disease': "Sin Enfermedad", 'legend_with_disease': "Con Enfermedad",
29
+ },
30
+ 'en': {
31
+ 'page_title': "Cardiovascular Risk Analysis", 'page_icon': "馃┖",
32
+ 'title': "Interactive Dashboard of Cardiovascular Risk Factors 馃┖",
33
+ 'lang_button': "Espa帽ol / English",
34
+ 'tab1': "馃敟 Correlations", 'tab2': "馃搳 Categorical Analysis", 'tab3': "馃幓 Numerical Analysis",
35
+ 'corr_header': "Correlation Between Variables",
36
+ 'corr_desc': "A heatmap to quickly identify linear relationships. Values close to +1 (deep red) or -1 (deep blue) indicate a strong correlation.",
37
+ 'dict_header': "馃摉 Data Dictionary",
38
+ '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" },
39
+ 'cholesterol_labels': {1: 'Normal', 2: 'Above Normal', 3: 'Well Above Normal'}, 'gluc_labels': {1: 'Normal', 2: 'Above Normal', 3: 'Well Above Normal'},
40
+ 'binary_labels': {0: 'No', 1: 'Yes'}, 'cat_header': "Interactive Analysis of Categorical Variables",
41
+ 'cat_desc': "Select a variable to compare the number of patients (with and without disease) in each category.",
42
+ 'cat_select': "Select a categorical variable:", 'cat_plot_title': "Distribution by Cardiovascular Condition",
43
+ 'cat_axis_y': "Patient Count", 'num_header': "Interactive Analysis of Numerical Variables",
44
+ 'num_desc': "Select a variable to compare its distribution (age, weight, blood pressure) between healthy and sick patients.",
45
+ 'num_select': "Select a numerical variable:", 'num_plot_title': "Distribution of {} by Cardiovascular Condition",
46
+ 'legend_no_disease': "No Disease", 'legend_with_disease': "With Disease",
47
+ }
48
+ }
49
+
50
+ # --- L脫GICA DE LA APP (Sin cambios) ---
51
+ if 'lang' not in st.session_state:
52
+ st.session_state.lang = 'en'
53
+ def toggle_language():
54
+ st.session_state.lang = 'es' if st.session_state.lang == 'en' else 'en'
55
+ st.set_page_config(page_title=TEXTS[st.session_state.get('lang', 'en')]['page_title'], page_icon="馃┖", layout="wide")
56
+ texts = TEXTS[st.session_state.lang]
57
+
58
+ @st.cache_data
59
+ def load_data():
60
+ df = pd.read_csv('cardio_train.csv', sep=';')
61
+ df['age_years'] = (df['age'] / 365.25).round().astype(int)
62
+ df = df[(df['ap_hi'] >= 90) & (df['ap_hi'] <= 240) & (df['ap_lo'] >= 60) & (df['ap_lo'] <= 140)]
63
+ df.drop(columns=['id', 'age'], inplace=True)
64
+ return df
65
+ df = load_data()
66
+
67
+ # --- INTERFAZ ---
68
+ st.button(texts['lang_button'], on_click=toggle_language)
69
+ st.title(texts['title'])
70
+
71
+ tab_keys = ['tab1', 'tab2', 'tab3']
72
+ tab_labels = [texts[key] for key in tab_keys]
73
+ tab1, tab2, tab3 = st.tabs(tab_labels)
74
+
75
+ with tab1:
76
+ # (El c贸digo de la Tab 1 no cambia)
77
+ st.header(texts['corr_header']); st.write(texts['corr_desc'])
78
+ correlation_matrix = df.corr()
79
+ fig, ax = plt.subplots(figsize=(14, 10))
80
+ sns.heatmap(correlation_matrix, annot=True, fmt='.2f', cmap='coolwarm', ax=ax)
81
+ st.pyplot(fig)
82
+ with st.expander(texts['dict_header']):
83
+ for var, desc in texts['var_names'].items(): st.markdown(f"**{var}:** {desc}")
84
+
85
+ with tab2:
86
+ # (El c贸digo de la Tab 2 no cambia)
87
+ st.header(texts['cat_header']); st.write(texts['cat_desc'])
88
+ cat_vars_keys = ['cholesterol', 'gluc', 'smoke', 'alco', 'active']
89
+ selected_cat_var = st.selectbox(texts['cat_select'], options=cat_vars_keys, format_func=lambda var: texts['var_names'][var])
90
+ if selected_cat_var:
91
+ fig, ax = plt.subplots(figsize=(10, 6))
92
+ sns.countplot(x=selected_cat_var, hue='cardio', data=df, ax=ax, palette='pastel')
93
+ ax.set_title(f"{texts['var_names'][selected_cat_var]}", fontsize=16)
94
+ ax.set_xlabel(texts['var_names'][selected_cat_var], fontsize=12)
95
+ ax.set_ylabel(texts['cat_axis_y'], fontsize=12)
96
+ if selected_cat_var == 'cholesterol': ax.set_xticklabels([texts['cholesterol_labels'][i] for i in sorted(df[selected_cat_var].unique())])
97
+ elif selected_cat_var == 'gluc': ax.set_xticklabels([texts['gluc_labels'][i] for i in sorted(df[selected_cat_var].unique())])
98
+ else: ax.set_xticklabels([texts['binary_labels'][i] for i in sorted(df[selected_cat_var].unique())])
99
+ handles, _ = ax.get_legend_handles_labels(); ax.legend(handles, [texts['legend_no_disease'], texts['legend_with_disease']], title='Condici贸n')
100
+ st.pyplot(fig)
101
+
102
+ with tab3:
103
+ st.header(texts['num_header'])
104
+ st.write(texts['num_desc'])
105
+
106
+ num_vars_keys = ['age_years', 'height', 'weight', 'ap_hi', 'ap_lo']
107
+ selected_num_var = st.selectbox(texts['num_select'], options=num_vars_keys, format_func=lambda var: texts['var_names'][var])
108
+
109
+ if selected_num_var:
110
+ fig, ax = plt.subplots(figsize=(10, 6))
111
+ sns.violinplot(x='cardio', y=selected_num_var, data=df, ax=ax, palette='pastel')
112
+
113
+ # --- INICIO DE LA CORRECCI脫N ---
114
+ # Simplificamos la creaci贸n del t铆tulo para evitar errores
115
+ title_template = texts['num_plot_title']
116
+ variable_name = texts['var_names'][selected_num_var]
117
+ final_title = title_template.format(variable_name)
118
+ ax.set_title(final_title, fontsize=14)
119
+ # --- FIN DE LA CORRECCI脫N ---
120
+
121
+ ax.set_xticklabels([texts['legend_no_disease'], texts['legend_with_disease']])
122
+ ax.set_xlabel(None)
123
+ ax.set_ylabel(texts['var_names'][selected_num_var], fontsize=12)
124
+ st.pyplot(fig)
cardio_train.csv ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt CHANGED
@@ -1,3 +1,5 @@
1
- altair
2
- pandas
3
- streamlit
 
 
 
1
+ streamlit
2
+ pandas
3
+ numpy
4
+ matplotlib
5
+ seaborn