Spaces:
Sleeping
Sleeping
import gradio as gr | |
import pandas as pd | |
import matplotlib.pyplot as plt | |
def process_file(file): | |
# 读取CSV文件并创建DataFrame | |
df = pd.read_csv(file.name) | |
columns = df.columns.tolist() | |
print("文件已上传,表头为:", columns) # 调试信息 | |
# 返回前5行数据,更新下拉列表选项,并使其他控件可见 | |
return (df.head(), | |
gr.update(visible=True), | |
gr.update(choices=columns, visible=True), | |
gr.update(choices=columns, visible=True), | |
gr.update(visible=True)) | |
def update_slider(choice): | |
print("选择框的值:", choice) # 调试信息 | |
# 更新数轴控件的可见性 | |
return gr.update(visible=choice == "是") | |
def generate_output(file, col1, col2, choice, number): | |
df = pd.read_csv(file.name) | |
filtered_data = df[[col1, col2]].dropna() | |
plt.figure(figsize=(10, 6)) | |
plt.scatter(filtered_data[col1], filtered_data[col2]) | |
plt.xlabel(col1) | |
plt.ylabel(col2) | |
plt.title(f'Scatter plot of {col1} vs {col2}') | |
image_path = 'output.png' | |
plt.savefig(image_path) | |
plt.close() | |
return filtered_data.head(), image_path | |
with gr.Blocks() as demo: | |
file_input = gr.File(label="上传CSV文件", file_types=["csv"]) | |
df_display = gr.Dataframe(visible=False) | |
col1_dropdown = gr.Dropdown(label="选择列1", visible=False) | |
col2_dropdown = gr.Dropdown(label="选择列2", visible=False) | |
choice_radio = gr.Radio(["是", "否"], label="是否选择", visible=False) | |
slider = gr.Slider(minimum=2, maximum=7, step=1, label="选择数字", visible=False) | |
submit_button = gr.Button("提交") | |
output_image = gr.Image(visible=False) | |
# 文件上传后调用 process_file 函数 | |
file_input.upload(process_file, inputs=file_input, outputs=[df_display, col1_dropdown, col2_dropdown, choice_radio]) | |
# 选择框值改变时调用 update_slider 函数 | |
choice_radio.change(update_slider, inputs=choice_radio, outputs=slider) | |
# 点击提交按钮时调用 generate_output 函数 | |
submit_button.click(generate_output, inputs=[file_input, col1_dropdown, col2_dropdown, choice_radio, slider], outputs=[df_display, output_image]) | |
demo.launch() | |