Spaces:
Sleeping
Sleeping
import pandas as pd | |
import matplotlib.pyplot as plt | |
import gradio as gr | |
import tempfile | |
import warnings | |
warnings.filterwarnings(action='ignore', category=UserWarning) | |
# 设置中文字体和编码 | |
plt.rcParams['font.sans-serif'] = ['SimHei'] # 选择合适的中文字体,这里使用宋体 | |
plt.rcParams['axes.unicode_minus'] = False # 设置正常显示字符 | |
def process_data(file_name, column1, column2, is_continuous, bins): | |
# column1 = "身高" | |
# column2 = "心血管疾病" | |
# is_continuous = True | |
# bins = 5 | |
# 读取数据 | |
df = pd.read_csv(file_name) | |
data_x = df[column1] | |
data_y = df[column2] | |
# 自动判断column1的数据类型 | |
if is_continuous: | |
# 如果是连续值,则进行分组 | |
data_x = pd.qcut(data_x, q=bins, duplicates='drop') | |
else: | |
# 如果是离散值,则直接使用 | |
pass | |
# 统计每个身高分段中不同心血管疾病类别的数量 | |
counts = pd.crosstab(data_x, data_y) | |
# 绘制分段柱形图 | |
counts.plot(kind='bar') | |
# 设置 x 轴刻度标签横向显示 | |
plt.xticks(rotation=0) | |
plt.xlabel(column1, fontsize=12) | |
plt.ylabel(column2, fontsize=12) | |
# plt.legend(['不患病', '患病']) | |
plt.title(f'{column1}与{column2}的关系', fontsize=14) | |
# plt.show() | |
# 将图表保存为PNG图像文件 | |
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp: | |
temp_image_path = temp.name | |
plt.savefig(temp_image_path) | |
return df.head(), temp_image_path | |
# 创建Gradio界面 | |
iface = gr.Interface( | |
fn=process_data, | |
inputs=[ | |
gr.File(label="上传数据表格"), | |
gr.Textbox(label="指定第1个数据列名称"), | |
gr.Textbox(label="指定第2个数据列名称"), | |
gr.Checkbox(label="第1列数据是连续值类型", default=False), | |
gr.Slider(3, 6, label="如果第1列是连续值,要分为几组"), | |
], | |
outputs=[ | |
gr.Dataframe(type='pandas', label="数据表的前5行"), | |
gr.Image(type='filepath', label="柱形图") | |
], | |
title="数据分布可视化工具", | |
description="上传数据表格,指定列名称,查看特定数据列分布的可视化结果。" | |
) | |
iface.launch(share=True) |