Gradio 月活用户突破 100 万!

阅读更多
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()

dataframe 中的 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()

你可以结合此功能和 .double_click 监听器,通过更改 x_lim 来创建一些放大/缩小效果,x_lim 设置 x 轴的边界

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()

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