Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
import matplotlib.pyplot as plt
|
3 |
+
import gradio as gr
|
4 |
+
import tempfile
|
5 |
+
import warnings
|
6 |
+
|
7 |
+
warnings.filterwarnings(action='ignore', category=UserWarning)
|
8 |
+
|
9 |
+
# 设置中文字体和编码
|
10 |
+
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS'] # 选择合适的中文字体,这里使用宋体
|
11 |
+
plt.rcParams['axes.unicode_minus'] = False # 设置正常显示字符
|
12 |
+
|
13 |
+
def process_data(file_name, column1, column2, is_continuous, bins):
|
14 |
+
# 读取数据
|
15 |
+
df = pd.read_csv(file_name)
|
16 |
+
data_x = df[column1]
|
17 |
+
data_y = df[column2]
|
18 |
+
# 自动判断column1的数据类型
|
19 |
+
if is_continuous:
|
20 |
+
# 如果是连续值,则进行分组
|
21 |
+
data_x = pd.qcut(data_x, q=bins, duplicates='drop')
|
22 |
+
else:
|
23 |
+
# 如果是离散值,则直接使用
|
24 |
+
pass
|
25 |
+
# 统计每个身高分段中不同心血管疾病类别的数量
|
26 |
+
counts = pd.crosstab(data_x, data_y)
|
27 |
+
# 绘制分段柱形图
|
28 |
+
counts.plot(kind='bar')
|
29 |
+
# 设置 x 轴刻度标签横向显示
|
30 |
+
plt.xticks(rotation=0)
|
31 |
+
plt.xlabel(column1, fontsize=12)
|
32 |
+
plt.ylabel(column2, fontsize=12)
|
33 |
+
# plt.legend(['不患病', '患病'])
|
34 |
+
plt.title(f'{column1}与{column2}的关系', fontsize=14)
|
35 |
+
# plt.show()
|
36 |
+
|
37 |
+
# 将图表保存为PNG图像文件
|
38 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp:
|
39 |
+
temp_image_path = temp.name
|
40 |
+
plt.savefig(temp_image_path)
|
41 |
+
|
42 |
+
return df.head(), temp_image_path
|
43 |
+
|
44 |
+
# 创建Gradio界面
|
45 |
+
iface = gr.Interface(
|
46 |
+
fn=process_data,
|
47 |
+
inputs=[
|
48 |
+
gr.inputs.File(label="上传数据表格"),
|
49 |
+
gr.inputs.Textbox(label="指定第1个数据列名称"),
|
50 |
+
gr.inputs.Textbox(label="指定第2个数据列名称"),
|
51 |
+
gr.inputs.Checkbox(label="第1列数据是连续值类型", default=False),
|
52 |
+
gr.inputs.Number(label="如果第1列是连续值,要分为几组", optional=True),
|
53 |
+
],
|
54 |
+
outputs=[
|
55 |
+
gr.outputs.Dataframe(type='pandas', label="数据表的前5行"),
|
56 |
+
gr.outputs.Image(type='filepath', label="柱形图")
|
57 |
+
],
|
58 |
+
title="数据分布可视化工具",
|
59 |
+
description="上传数据表格,指定列名称,查看特定数据列分布的可视化结果。"
|
60 |
+
)
|
61 |
+
|
62 |
+
iface.launch(share=True)
|