Gradio Agents & MCP 黑客马拉松

获奖者
Gradio logo
  1. 数据科学和图表
  2. 创建图表

创建图表

Gradio 是创建高度可定制仪表盘的绝佳方式。Gradio 提供了三个原生绘图组件:gr.LinePlotgr.ScatterPlotgr.BarPlot。所有这些绘图都具有相同的 API。让我们看看如何设置它们。

使用 pd.Dataframe 创建图表

绘图组件接受 pandas Dataframe 作为其值。绘图还接受 xy 参数,它们分别表示 x 轴和 y 轴的列名。这是一个简单的示例:

import gradio as gr
import pandas as pd
import numpy as np
import random

df = pd.DataFrame({
    'height': np.random.randint(50, 70, 25),
    'weight': np.random.randint(120, 320, 25),
    'age': np.random.randint(18, 65, 25),
    'ethnicity': [random.choice(["white", "black", "asian"]) for _ in range(25)]
})

with gr.Blocks() as demo:
    gr.LinePlot(df, x="weight", y="height")

demo.launch()

所有绘图组件都具有相同的 API,因此你可以将其替换为 gr.ScatterPlot

import gradio as gr
from data import df

with gr.Blocks() as demo:
    gr.ScatterPlot(df, x="weight", y="height")

demo.launch()

数据框中的 y 轴列应为数值类型,而 x 轴列可以是字符串、数字、类别或日期时间。

import gradio as gr
from data import df

with gr.Blocks() as demo:
    gr.ScatterPlot(df, x="ethnicity", y="height")

demo.launch()

按颜色拆分序列

你可以使用 color 参数将图表拆分为多个系列。

import gradio as gr
from data import df

with gr.Blocks() as demo:
    gr.ScatterPlot(df, x="weight", y="height", color="ethnicity")

demo.launch()

如果你希望为特定系列分配颜色,请使用 color_map 参数,例如 gr.ScatterPlot(..., color_map={'white': '#FF9988', 'asian': '#88EEAA', 'black': '#333388'})

颜色列也可以是数值类型。

import gradio as gr
from data import df

with gr.Blocks() as demo:
    gr.ScatterPlot(df, x="weight", y="height", color="age")

demo.launch()

聚合值

你可以使用 x_biny_aggregate 参数将值聚合成组。如果你的 x 轴是数值类型,提供 x_bin 将创建直方图风格的分箱。

import gradio as gr
from data import df

with gr.Blocks() as demo:
    gr.BarPlot(df, x="weight", y="height", x_bin=10, y_aggregate="sum")

demo.launch()

如果你的 x 轴是字符串类型,它们将自动作为类别分箱。

import gradio as gr
from data import df

with gr.Blocks() as demo:
    gr.BarPlot(df, x="ethnicity", y="height", y_aggregate="mean")

demo.launch()

选择区域

你可以使用 .select 监听器来选择图表的区域。在下方图表上点击并拖动以选择图表的一部分。

import gradio as gr
from data import df

with gr.Blocks() as demo:
    plt = gr.LinePlot(df, x="weight", y="height")
    selection_total = gr.Number(label="Total Weight of Selection")

    def select_region(selection: gr.SelectData):
        min_w, max_w = selection.index
        return df[(df["weight"] >= min_w) & (df["weight"] <= max_w)]["weight"].sum()

    plt.select(select_region, None, selection_total)

demo.launch()

你可以结合 .select.double_click 监听器,通过改变设置 x 轴边界的 x_lim 来创建缩放效果。

import gradio as gr
from data import df

with gr.Blocks() as demo:
    plt = gr.LinePlot(df, x="weight", y="height")

    def select_region(selection: gr.SelectData):
        min_w, max_w = selection.index
        return gr.LinePlot(x_lim=(min_w, max_w)) 

    plt.select(select_region, None, plt)
    plt.double_click(lambda: gr.LinePlot(x_lim=None), None, plt)

demo.launch()

如果你有多个具有相同 x 列的图表,你的事件监听器可以针对所有其他图表的 x 轴限制,使 x 轴保持同步。

import gradio as gr
from data import df

with gr.Blocks() as demo:
    plt1 = gr.LinePlot(df, x="weight", y="height")
    plt2 = gr.BarPlot(df, x="weight", y="age", x_bin=10)
    plots = [plt1, plt2]

    def select_region(selection: gr.SelectData):
        min_w, max_w = selection.index
        return [gr.LinePlot(x_lim=(min_w, max_w))] * len(plots) 

    for plt in plots:
        plt.select(select_region, None, plots)
        plt.double_click(lambda: [gr.LinePlot(x_lim=None)] * len(plots), None, plots)

demo.launch()

创建交互式仪表盘

看看如何创建一个交互式仪表盘,其中图表是其他组件的函数。

import gradio as gr
from data import df

with gr.Blocks() as demo:
    with gr.Row():
        ethnicity = gr.Dropdown(["all", "white", "black", "asian"], value="all")
        max_age = gr.Slider(18, 65, value=65)

    def filtered_df(ethnic, age):
        _df = df if ethnic == "all" else df[df["ethnicity"] == ethnic]
        _df = _df[_df["age"] < age]
        return _df

    gr.ScatterPlot(filtered_df, inputs=[ethnicity, max_age], x="weight", y="height", title="Weight x Height")
    gr.LinePlot(filtered_df, inputs=[ethnicity, max_age], x="age", y="height", title="Age x Height")

demo.launch()

过滤和控制可视化中呈现的数据就是这么简单!