1. 数据科学与图表
  2. 时间图

时间图

创建带有时间x轴的可视化是一个常见的用例。让我们深入探讨!

使用pd.Dataframe创建图表

时间图需要在x轴上有一个日期时间列。以下是一个使用一些航班数据的简单示例:

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

from datetime import datetime, timedelta
now = datetime.now()

df = pd.DataFrame({
    'time': [now - timedelta(minutes=5*i) for i in range(25)],
    'price': np.random.randint(100, 1000, 25),
    'origin': [random.choice(["DFW", "DAL", "HOU"]) for _ in range(25)],
    'destination': [random.choice(["JFK", "LGA", "EWR"]) for _ in range(25)],
})

with gr.Blocks() as demo:
    gr.LinePlot(df, x="time", y="price")
    gr.ScatterPlot(df, x="time", y="price", color="origin")

demo.launch()

按时间聚合

你可能希望按时间桶对数据进行分箱。使用 x_bin 来实现,使用带有 "s"、"m"、"h" 或 "d" 的字符串后缀,例如 "15m" 或 "1d"。

import gradio as gr
from data import df

with gr.Blocks() as demo:
    plot = gr.BarPlot(df, x="time", y="price", x_bin="10m")

    bins = gr.Radio(["10m", "30m", "1h"], label="Bin Size")
    bins.change(lambda bins: gr.BarPlot(x_bin=bins), bins, plot)

demo.launch()

日期时间组件

你可以使用gr.DateTime来接受输入的日期时间数据。这对于定义数据的x轴范围的图表非常有效。

import gradio as gr
from data import df

with gr.Blocks() as demo:
    with gr.Row():
        start = gr.DateTime("now - 24h")
        end = gr.DateTime("now")
        apply_btn = gr.Button("Apply")
    plot = gr.LinePlot(df, x="time", y="price")

    apply_btn.click(lambda start, end: gr.BarPlot(x_lim=[start, end]), [start, end], plot)
    
demo.launch()

注意gr.DateTime可以接受完整的日期时间字符串,或者使用now - [0-9]+[smhd]格式的简写来引用过去的时间。

你经常会遇到许多时间图,在这种情况下,你可能希望保持x轴同步。DateTimeRange自定义组件可以保持一组时间图同步,并且还使用图的.select监听器,允许你在保持图同步的同时放大图。

因为它是一个自定义组件,你首先需要pip install gradio_datetimerange。然后运行以下代码:

import gradio as gr
from gradio_datetimerange import DateTimeRange
from data import df

with gr.Blocks() as demo:
    daterange = DateTimeRange(["now - 24h", "now"])
    plot1 = gr.LinePlot(df, x="time", y="price")
    plot2 = gr.LinePlot(df, x="time", y="price", color="origin")
    daterange.bind([plot1, plot2])

demo.launch()

尝试在图表中缩放,看看DateTimeRange如何更新。所有图表都会同步更新它们的x_lim。组件中还有一个“返回”链接,允许您快速放大和缩小。

实时数据

在许多情况下,您处理的是实时的、动态的数据,而不是静态的数据框。在这种情况下,您可以使用gr.Timer()定期更新图表。假设有一个get_data方法可以获取最新的数据框:

with gr.Blocks() as demo:
    timer = gr.Timer(5)
    plot1 = gr.BarPlot(x="time", y="price")
    plot2 = gr.BarPlot(x="time", y="price", color="origin")

    timer.tick(lambda: [get_data(), get_data()], outputs=[plot1, plot2])

你也可以使用 every 简写来将一个 Timer 附加到一个具有函数值的组件上:

with gr.Blocks() as demo:
    timer = gr.Timer(5)
    plot1 = gr.BarPlot(get_data, x="time", y="price", every=timer)
    plot2 = gr.BarPlot(get_data, x="time", y="price", color="origin", every=timer)