File size: 7,344 Bytes
99a0c40 ae9bd10 99a0c40 67d7353 99a0c40 |
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 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 |
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from plot_registry import PlotRegistry
# -------------------------------------------------
# Sayfa ayarları
# -------------------------------------------------
st.set_page_config(
page_title="Matplotlib Veri Görselleştirme Aracı",
layout="wide"
)
st.title("📊 Matplotlib Tabanlı Veri Görselleştirme Aracı")
# -------------------------------------------------
# Yardımcı fonksiyonlar
# -------------------------------------------------
def detect_columns(df: pd.DataFrame):
numeric = []
categorical = []
ignore = []
for col in df.columns:
nunique = df[col].nunique(dropna=True)
ratio = nunique / max(len(df), 1)
if pd.api.types.is_numeric_dtype(df[col]):
if ratio < 0.05:
categorical.append(col)
else:
numeric.append(col)
else:
if ratio > 0.7:
ignore.append(col)
else:
categorical.append(col)
return numeric, categorical, ignore
def eda_summary(df: pd.DataFrame):
st.subheader("🔍 Basit EDA Özeti")
st.markdown("**Veri Seti**")
st.dataframe(df.head())
c1, c2 = st.columns(2)
with c1:
st.markdown("**Veri Boyutu**")
st.write(df.shape)
st.markdown("**Eksik Değerler**")
st.dataframe(df.isnull().sum().to_frame("Eksik Sayısı")[df.isnull().sum() > 0])
with c2:
st.markdown("**Sayısal Alan İstatistikleri**")
st.dataframe(df.describe().T)
# -------------------------------------------------
# Plot registry
# -------------------------------------------------
registry = PlotRegistry("/app/src/plots.json")
# -------------------------------------------------
# Dosya yükleme
# -------------------------------------------------
uploaded = st.file_uploader(
"📁 CSV / XLS / XLSX dosyası yükleyin",
type=["csv", "xls", "xlsx"]
)
if not uploaded:
st.info("Başlamak için bir veri seti yükleyin.")
st.stop()
# -------------------------------------------------
# Veri okuma
# -------------------------------------------------
if uploaded.name.endswith(".csv"):
df = pd.read_csv(uploaded)
else:
df = pd.read_excel(uploaded)
st.success("Veri başarıyla yüklendi")
# -------------------------------------------------
# EDA
# -------------------------------------------------
eda_summary(df)
# -------------------------------------------------
# Alan tespiti
# -------------------------------------------------
numeric_cols, cat_cols, ignore_cols = detect_columns(df)
st.subheader("🧩 Alan Türleri (Düzenlenebilir)")
c1, c2, c3 = st.columns(3)
with c1:
num_options = df.columns
num_default = [c for c in numeric_cols if c in num_options]
numeric_cols = st.multiselect(
"🔢 Sayısal Alanlar",
options=num_options,
default=num_default
)
with c2:
cat_options = df.columns
cat_default = [c for c in cat_cols if c in cat_options]
cat_cols = st.multiselect(
"🏷️ Kategorik Alanlar",
options=cat_options,
default=cat_default
)
with c3:
ignore_cols = st.multiselect(
"🚫 Grafik Dışı Alanlar",
options=df.columns,
default=ignore_cols
)
usable_cols = numeric_cols + cat_cols
# -------------------------------------------------
# Grafik seçimi
# -------------------------------------------------
st.divider()
st.subheader("📈 Grafik Seçimi")
groups = registry.get_groups()
group = st.selectbox("Grafik Grubu", groups)
plots = registry.get_plots_in_group(group)
plot_key = st.selectbox(
"Grafik Türü",
list(plots.keys())
)
plot_info = registry.get_plot(group, plot_key)
# -------------------------------------------------
# Açıklama
# -------------------------------------------------
st.info(f"**Ne zaman kullanılır?**\n\n{plot_info.get('when_to_use','')}")
# -------------------------------------------------
# Alan seçimi
# -------------------------------------------------
st.subheader("🧮 Grafik Alanları")
inputs = plot_info.get("inputs", [])
vars_selected = {}
for inp in inputs:
if inp in ["x", "y"]:
vars_selected[inp] = st.selectbox(
f"{inp.upper()} alanı",
options=usable_cols if inp != "y" else usable_cols
)
# -------------------------------------------------
# Grafik özel ayarları
# -------------------------------------------------
st.subheader("⚙️ Grafik Ayarları")
PALETTES = {
"Default": plt.rcParams['axes.prop_cycle'].by_key()['color'],
"Pastel": ["#AEC6CF", "#FFB347", "#B39EB5", "#77DD77"],
"Bold": ["#e41a1c", "#377eb8", "#4daf4a", "#984ea3"],
"Grayscale": ["#222222", "#555555", "#888888", "#BBBBBB"]
}
options = {}
opts = list(plot_info.get("options", {}).items())
if opts:
cols = st.columns(len(opts))
for i, (opt, default) in enumerate(opts):
col = cols[i % len(cols)]
if opt == "color":
palette_name = col.selectbox("🎨 Palet", PALETTES.keys())
palette = PALETTES[palette_name]
options[opt] = col.color_picker("Tek Renk", palette[0])
else:
options[opt] = col.text_input(opt, value=str(default) if default is not None else "")
else:
st.write("Bu grafik tipi için özelleştirilebilir ayar yok.")
# -------------------------------------------------
# Genel ayarlar
# -------------------------------------------------
st.subheader("🖼️ Genel Görsel Ayarlar")
col1, col2 = st.columns([1, 4])
with col1:
fig_w = st.number_input("Figür Genişliği", 4, 20, 8)
fig_h = st.number_input("Figür Yüksekliği", 4, 20, 5)
with col2:
title = st.text_input("Başlık", "Grafik Başlığı")
xlabel = st.text_input("X Etiketi", vars_selected.get("x", ""))
ylabel = st.text_input("Y Etiketi", vars_selected.get("y", ""))
# -------------------------------------------------
# Grafik çizimi
# -------------------------------------------------
st.divider()
st.subheader("📊 Grafik")
fig, ax = plt.subplots(figsize=(fig_w, fig_h))
# options string -> python obj
clean_options = options
exec_code, display_code = registry.generate_code(
group=group,
plot_key=plot_key,
variables={
"x": f"df['{vars_selected.get('x')}']",
"y": f"df['{vars_selected.get('y')}']"
},
user_options=options,
figsize=(fig_w, fig_h),
title=title,
xlabel=xlabel,
ylabel=ylabel
)
# Grafik kodunu çalıştır (try/except)
try:
exec(exec_code, {"df": df, "plt": plt, "ax": ax})
except Exception as e:
st.error("Grafik oluşturulurken hata oluştu.")
st.exception(e)
else:
st.pyplot(fig)
# -------------------------------------------------
# PNG indirme
# -------------------------------------------------
import io
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=300)
buf.seek(0)
st.download_button(
"⬇️ Grafiği PNG olarak indir",
data=buf,
file_name="grafik.png",
mime="image/png"
)
# -------------------------------------------------
# Kod gösterimi
# -------------------------------------------------
st.subheader("🐍 Python Kod Çıktısı (Notebook Uyumlu)")
st.code(display_code, language="python") |