Spaces:
Sleeping
Sleeping
Update app.py
Browse files4 unmodified lines56789106 unmodified lines171819202122235 unmodified lines29303132333435363738394041424344454647484950515253545556575859606162636465666768697071727324 unmodified lines98991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521 unmodified line1541551561571581591604 unmodified linesimport ioimport base64from PIL import Image# Configuración de la páginast.set_page_config(6 unmodified linesst.title("📊 Visualizador de Datos")st.markdown("### Carga tu archivo CSV o Excel y crea visualizaciones personalizadas")# Función para cargar el archivodef load_data():uploaded_file = st.file_uploader("Carga tu archivo CSV o Excel", type=["csv", "xlsx", "xls"])5 unmodified lineselse:data = pd.read_excel(uploaded_file)return dataexcept Exception as e:st.error(f"Error al cargar el archivo: {e}")return Nonereturn None# Función para generar gráficosdef create_plot(data, x_col, y_col, plot_type):fig, ax = plt.subplots(figsize=(10, 6))if plot_type == "Barras":sns.barplot(x=x_col, y=y_col, data=data, ax=ax)elif plot_type == "Barras (Count)":# Crear conteo de valorescount_data = data[x_col].value_counts().reset_index()count_data.columns = [x_col, 'count']sns.barplot(x=x_col, y='count', data=count_data, ax=ax)plt.ylabel('Frecuencia')elif plot_type == "Líneas":sns.lineplot(x=x_col, y=y_col, data=data, ax=ax)elif plot_type == "Dispersión":sns.scatterplot(x=x_col, y=y_col, data=data, ax=ax)elif plot_type == "Histograma":sns.histplot(data[x_col], ax=ax)plt.xlabel(x_col)elif plot_type == "Boxplot":sns.boxplot(x=x_col, y=y_col, data=data, ax=ax)elif plot_type == "Violín":sns.violinplot(x=x_col, y=y_col, data=data, ax=ax)elif plot_type == "Pastel":data[x_col].value_counts().plot.pie(autopct='%1.1f%%', ax=ax)plt.ylabel('')elif plot_type == "Mapa de calor":if len(data) > 100:sample_data = data.sample(100)else:sample_data = datacorrelation = sample_data.select_dtypes(include=['float64', 'int64']).corr()sns.heatmap(correlation, annot=True, cmap='coolwarm', ax=ax)plt.tight_layout()return fig24 unmodified lineswith col2:st.info(f"Número de columnas: {data.shape[1]}")# Selección de columnas y tipo de gráficost.subheader("Crear visualización")col1, col2, col3 = st.columns(3)with col1:plot_type = st.selectbox("Tipo de gráfico",["Barras", "Barras (Count)", "Líneas", "Dispersión", "Histograma", "Boxplot", "Violín", "Pastel", "Mapa de calor"])# Opciones de columnas basadas en el tipo de gráficonumeric_cols = data.select_dtypes(include=['float64', 'int64']).columns.tolist()categorical_cols = data.select_dtypes(include=['object']).columns.tolist()all_cols = data.columns.tolist()with col2:if plot_type == "Histograma":x_col = st.selectbox("Selecciona la columna para el histograma", numeric_cols)y_col = Noneelif plot_type == "Mapa de calor":x_col = "Correlación"y_col = "Correlación"elif plot_type == "Pastel":x_col = st.selectbox("Selecciona la columna para el gráfico de pastel", categorical_cols if categorical_cols else all_cols)y_col = Noneelif plot_type == "Barras (Count)":x_col = st.selectbox("Selecciona la columna para contar frecuencias", all_cols)y_col = "count" # Valor especial para indicar que se usará conteoelse:x_options = categorical_cols + numeric_cols if categorical_cols else all_colsx_col = st.selectbox("Selecciona la columna para el eje X", x_options)with col3:if plot_type not in ["Histograma", "Pastel", "Mapa de calor", "Barras (Count)"]:y_col = st.selectbox("Selecciona la columna para el eje Y", numeric_cols if numeric_cols else all_cols)# Crear gráficoif st.button("Generar visualización"):try:st.subheader("Visualización")fig = create_plot(data, x_col, y_col, plot_type)st.pyplot(fig)# Botón para descargar la imagenst.markdown(get_image_download_link(fig,f"{plot_type}_{x_col}_{y_col if y_col else ''}","📥 Descargar imagen"),unsafe_allow_html=True1 unmodified lineexcept Exception as e:st.error(f"Error al generar el gráfico: {e}")st.info("Sugerencia: Verifica que las columnas seleccionadas sean compatibles con el tipo de gráfico.")# Ejecutar la aplicaciónif __name__ == "__main__":4 unmodified lines567891011126 unmodified lines192021222324255 unmodified lines31323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113224 unmodified lines1571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142151 unmodified line2172182192202212222234 unmodified linesimport ioimport base64from PIL import Imageimport numpy as npfrom datetime import datetime# Configuración de la páginast.set_page_config(6 unmodified linesst.title("📊 Visualizador de Datos")st.markdown("### Carga tu archivo CSV o Excel y crea visualizaciones personalizadas")# Función para cargar el archivo y procesar fechasdef load_data():uploaded_file = st.file_uploader("Carga tu archivo CSV o Excel", type=["csv", "xlsx", "xls"])5 unmodified lineselse:data = pd.read_excel(uploaded_file)# Procesar la columna de fecha si existeif 'HML_TXDATE' in data.columns:try:# Convertir a datetimedata['HML_TXDATE'] = pd.to_datetime(data['HML_TXDATE'])# Extraer el día de la semanadata['DIA_SEMANA'] = data['HML_TXDATE'].dt.day_name()# Crear una columna con el formato español (opcional)dias_esp = {'Monday': 'Lunes','Tuesday': 'Martes','Wednesday': 'Miércoles','Thursday': 'Jueves','Friday': 'Viernes','Saturday': 'Sábado','Sunday': 'Domingo'}data['DIA_SEMANA_ESP'] = data['DIA_SEMANA'].map(dias_esp)# Extraer otras componentes de tiempo útilesdata['HORA'] = data['HML_TXDATE'].dt.hourdata['MES'] = data['HML_TXDATE'].dt.monthdata['AÑO'] = data['HML_TXDATE'].dt.yearst.success("✅ Columna de fecha 'HML_TXDATE' procesada correctamente")except Exception as e:st.warning(f"No se pudo procesar la columna de fecha: {e}")return dataexcept Exception as e:st.error(f"Error al cargar el archivo: {e}")return Nonereturn None# Función para generar gráficos basados en conteosdef create_count_plot(data, x_col, plot_type):fig, ax = plt.subplots(figsize=(12, 6))# Preparar datos de conteoif x_col in data.columns:# Eliminar valores nulos para el conteovalid_data = data[x_col].dropna()if plot_type == "Barras":# Contar valores y ordenar por frecuenciacount_data = valid_data.value_counts().reset_index()count_data.columns = [x_col, 'count']# Ordenar por conteo de mayor a menorcount_data = count_data.sort_values('count', ascending=False)# Limitar a los 20 valores más frecuentes para mejor visualizaciónif len(count_data) > 20:count_data = count_data.head(20)plt.title(f"Top 20 valores más frecuentes - {x_col}")else:plt.title(f"Frecuencia de valores - {x_col}")# Crear gráfico de barrassns.barplot(x=x_col, y='count', data=count_data, ax=ax)plt.xticks(rotation=45, ha='right')plt.ylabel('Frecuencia')plt.tight_layout()elif plot_type == "Pastel":# Contar valorescounts = valid_data.value_counts()# Si hay muchos valores únicos, mostrar solo los top 10if len(counts) > 10:# Guardar el resto como "Otros"otros = pd.Series({'Otros': counts[10:].sum()})counts = pd.concat([counts[:10], otros])plt.title(f"Top 10 valores más frecuentes - {x_col}")else:plt.title(f"Distribución de valores - {x_col}")# Crear gráfico de pastelcounts.plot.pie(autopct='%1.1f%%', ax=ax)plt.ylabel('')elif plot_type == "Histograma":# Solo aplicable a datos numéricosif pd.api.types.is_numeric_dtype(valid_data):sns.histplot(valid_data, kde=True, ax=ax)plt.xlabel(x_col)plt.ylabel('Frecuencia')plt.title(f"Distribución de {x_col}")else:plt.text(0.5, 0.5, "El histograma solo es aplicable a datos numéricos",ha='center', va='center', transform=ax.transAxes)else:plt.text(0.5, 0.5, f"Columna '{x_col}' no encontrada en el dataset",ha='center', va='center', transform=ax.transAxes)plt.tight_layout()return fig24 unmodified lineswith col2:st.info(f"Número de columnas: {data.shape[1]}")# Mostrar lista de columnas disponiblesst.subheader("Columnas disponibles")all_cols = data.columns.tolist()# Identificar tipo de datos para cada columnacol_types = {}for col in all_cols:if pd.api.types.is_numeric_dtype(data[col]):col_types[col] = "Numérico"elif pd.api.types.is_datetime64_dtype(data[col]):col_types[col] = "Fecha/Hora"else:col_types[col] = "Texto/Categórico"# Mostrar tipos de columnascol_type_df = pd.DataFrame(list(col_types.items()), columns=['Columna', 'Tipo'])st.dataframe(col_type_df)# Selección de columnas y tipo de gráficost.subheader("Crear visualización")col1, col2 = st.columns(2)with col1:# Visualizaciones basadas en conteoplot_type = st.selectbox("Tipo de gráfico",["Barras", "Pastel", "Histograma"])with col2:# Mostrar opciones especiales para día de la semana si existeif 'DIA_SEMANA_ESP' in data.columns:use_day_of_week = st.checkbox("¿Analizar por día de la semana?")if use_day_of_week:x_col = "DIA_SEMANA_ESP"else:x_col = st.selectbox("Selecciona la columna para analizar", all_cols)else:x_col = st.selectbox("Selecciona la columna para analizar", all_cols)# Crear gráficoif st.button("Generar visualización"):try:st.subheader("Visualización")fig = create_count_plot(data, x_col, plot_type)st.pyplot(fig)# Botón para descargar la imagenst.markdown(get_image_download_link(fig,f"{plot_type}_{x_col}","📥 Descargar imagen"),unsafe_allow_html=True1 unmodified lineexcept Exception as e:st.error(f"Error al generar el gráfico: {e}")st.info("Sugerencia: Verifica que la columna seleccionada sea compatible con el tipo de gráfico.")# Ejecutar la aplicaciónif __name__ == "__main__":
app.py+124-61