Team Ai
Apppublic

abdullatifkaban/matplotlib-visualizer

sourceHugging Facemitupdated 10mo agoView on Hugging Face
0likes
streamlit_app.py279 linesDownload Raw Back to src
1import streamlit as st2import pandas as pd3import numpy as np4import matplotlib.pyplot as plt5 6from plot_registry import PlotRegistry7 8 9# -------------------------------------------------10# Sayfa ayarları11# -------------------------------------------------12st.set_page_config(13    page_title="Matplotlib Veri Görselleştirme Aracı",14    layout="wide"15)16 17st.title("📊 Matplotlib Tabanlı Veri Görselleştirme Aracı")18 19 20# -------------------------------------------------21# Yardımcı fonksiyonlar22# -------------------------------------------------23def detect_columns(df: pd.DataFrame):24    numeric = []25    categorical = []26    ignore = []27 28    for col in df.columns:29        nunique = df[col].nunique(dropna=True)30        ratio = nunique / max(len(df), 1)31 32        if pd.api.types.is_numeric_dtype(df[col]):33            if ratio < 0.05:34                categorical.append(col)35            else:36                numeric.append(col)37        else:38            if ratio > 0.7:39                ignore.append(col)40            else:41                categorical.append(col)42 43    return numeric, categorical, ignore44 45 46def eda_summary(df: pd.DataFrame):47    st.subheader("🔍 Basit EDA Özeti")48 49    st.markdown("**Veri Seti**")50    st.dataframe(df.head())51 52    c1, c2 = st.columns(2)53 54    with c1:55        st.markdown("**Veri Boyutu**")56        st.write(df.shape)57 58        st.markdown("**Eksik Değerler**")59        st.dataframe(df.isnull().sum().to_frame("Eksik Sayısı")[df.isnull().sum() > 0])60 61    with c2:62        st.markdown("**Sayısal Alan İstatistikleri**")63        st.dataframe(df.describe().T)64 65 66# -------------------------------------------------67# Plot registry68# -------------------------------------------------69registry = PlotRegistry("/app/src/plots.json")70 71 72# -------------------------------------------------73# Dosya yükleme74# -------------------------------------------------75uploaded = st.file_uploader(76    "📁 CSV / XLS / XLSX dosyası yükleyin",77    type=["csv", "xls", "xlsx"]78)79 80if not uploaded:81    st.info("Başlamak için bir veri seti yükleyin.")82    st.stop()83 84# -------------------------------------------------85# Veri okuma86# -------------------------------------------------87if uploaded.name.endswith(".csv"):88    df = pd.read_csv(uploaded)89else:90    df = pd.read_excel(uploaded)91 92st.success("Veri başarıyla yüklendi")93 94# -------------------------------------------------95# EDA96# -------------------------------------------------97eda_summary(df)98 99# -------------------------------------------------100# Alan tespiti101# -------------------------------------------------102 103numeric_cols, cat_cols, ignore_cols = detect_columns(df)104 105st.subheader("🧩 Alan Türleri (Düzenlenebilir)")106 107c1, c2, c3 = st.columns(3)108 109with c1:110    num_options = df.columns111    num_default = [c for c in numeric_cols if c in num_options]112 113    numeric_cols = st.multiselect(114        "🔢 Sayısal Alanlar",115        options=num_options,116        default=num_default117    )118 119 120with c2:121    cat_options = df.columns122    cat_default = [c for c in cat_cols if c in cat_options]123 124    cat_cols = st.multiselect(125        "🏷️ Kategorik Alanlar",126        options=cat_options,127        default=cat_default128    )129 130 131with c3:132    ignore_cols = st.multiselect(133        "🚫 Grafik Dışı Alanlar",134        options=df.columns,135        default=ignore_cols136    ) 137 138usable_cols = numeric_cols + cat_cols139 140 141# -------------------------------------------------142# Grafik seçimi143# -------------------------------------------------144st.divider()145st.subheader("📈 Grafik Seçimi")146 147groups = registry.get_groups()148 149group = st.selectbox("Grafik Grubu", groups)150plots = registry.get_plots_in_group(group)151 152plot_key = st.selectbox(153    "Grafik Türü",154    list(plots.keys())155)156 157plot_info = registry.get_plot(group, plot_key)158 159# -------------------------------------------------160# Açıklama161# -------------------------------------------------162st.info(f"**Ne zaman kullanılır?**\n\n{plot_info.get('when_to_use','')}")163 164# -------------------------------------------------165# Alan seçimi166# -------------------------------------------------167st.subheader("🧮 Grafik Alanları")168 169inputs = plot_info.get("inputs", [])170 171vars_selected = {}172 173for inp in inputs:174    if inp in ["x", "y"]:175        vars_selected[inp] = st.selectbox(176            f"{inp.upper()} alanı",177            options=usable_cols if inp != "y" else usable_cols178        )179 180# -------------------------------------------------181# Grafik özel ayarları182# -------------------------------------------------183st.subheader("⚙️ Grafik Ayarları")184 185PALETTES = {186    "Default": plt.rcParams['axes.prop_cycle'].by_key()['color'],187    "Pastel": ["#AEC6CF", "#FFB347", "#B39EB5", "#77DD77"],188    "Bold": ["#e41a1c", "#377eb8", "#4daf4a", "#984ea3"],189    "Grayscale": ["#222222", "#555555", "#888888", "#BBBBBB"]190}191 192 193options = {}194opts = list(plot_info.get("options", {}).items())195if opts:196    cols = st.columns(len(opts))197    for i, (opt, default) in enumerate(opts):198        col = cols[i % len(cols)]199        if opt == "color":200            palette_name = col.selectbox("🎨 Palet", PALETTES.keys())201            palette = PALETTES[palette_name]202            options[opt] = col.color_picker("Tek Renk", palette[0])203        else:204            options[opt] = col.text_input(opt, value=str(default) if default is not None else "")205else:206    st.write("Bu grafik tipi için özelleştirilebilir ayar yok.")207 208 209# -------------------------------------------------210# Genel ayarlar211# -------------------------------------------------212st.subheader("🖼️ Genel Görsel Ayarlar")213 214col1, col2 = st.columns([1, 4])215 216with col1:217    fig_w = st.number_input("Figür Genişliği", 4, 20, 8)218    fig_h = st.number_input("Figür Yüksekliği", 4, 20, 5)219 220with col2:221    title = st.text_input("Başlık", "Grafik Başlığı")222    xlabel = st.text_input("X Etiketi", vars_selected.get("x", ""))223    ylabel = st.text_input("Y Etiketi", vars_selected.get("y", ""))224 225# -------------------------------------------------226# Grafik çizimi227# -------------------------------------------------228st.divider()229st.subheader("📊 Grafik")230 231fig, ax = plt.subplots(figsize=(fig_w, fig_h))232 233# options string -> python obj234clean_options = options235 236exec_code, display_code = registry.generate_code(237    group=group,238    plot_key=plot_key,239    variables={240        "x": f"df['{vars_selected.get('x')}']",241        "y": f"df['{vars_selected.get('y')}']"242    },243    user_options=options,244    figsize=(fig_w, fig_h),245    title=title,246    xlabel=xlabel,247    ylabel=ylabel248)249 250# Grafik kodunu çalıştır (try/except)251try:252    exec(exec_code, {"df": df, "plt": plt, "ax": ax})253except Exception as e:254    st.error("Grafik oluşturulurken hata oluştu.")255    st.exception(e)256else:257    st.pyplot(fig)258 259# -------------------------------------------------260# PNG indirme261# -------------------------------------------------262import io263 264buf = io.BytesIO()265fig.savefig(buf, format="png", dpi=300)266buf.seek(0)267 268st.download_button(269    "⬇️ Grafiği PNG olarak indir",270    data=buf,271    file_name="grafik.png",272    mime="image/png"273)274 275# -------------------------------------------------276# Kod gösterimi277# -------------------------------------------------278st.subheader("🐍 Python Kod Çıktısı (Notebook Uyumlu)")279st.code(display_code, language="python")