Rust 中的數據可視化指南

可視化是數據分析和解釋的一個關鍵方面。雖然 Rust 主要以其性能和安全特性而聞名,但它也爲數據可視化提供了強大的工具。在這個全面的指南中,我們將深入研究 Rust 中的數據可視化世界,探索庫,技術和編碼示例,以幫助你爲數據項目創建令人驚歎的可視化。

Rust 中的數據可視化庫

Plotters

Plotters 庫是一個靈活且功能豐富的 Rust 繪圖庫。它支持各種圖表類型,包括折線圖、條形圖、散點圖和直方圖。Plotters 支持各種類型的後端,包括 GTK/Cairo 和 WebAssembly 等,確保了高質量的圖形輸出。爲創建可視化提供了一個簡單而直觀的 API。

讓我們看一下使用 Plotters 畫一個二次函數的實際示例。

Plotters 依賴於 Ubuntu 的庫:

sudo apt install pkg-config libfreetype6-dev libfontconfig1-dev

要使用 Plotters,需要將 Plotters crate 添加到 Cargo.toml 中:

[dependencies]
plotters = "0.3.3"

在 main.rs 中,寫入以下代碼:

use plotters::prelude::*;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let root = BitMapBackend::new("plotters-doc-data/0.png"(640, 480)).into_drawing_area();
    root.fill(&WHITE)?;
    let mut chart = ChartBuilder::on(&root)
        .caption("y=x^2"("sans-serif", 50).into_font())
        .margin(5)
        .x_label_area_size(30)
        .y_label_area_size(30)
        .build_cartesian_2d(-1f32..1f32, -0.1f32..1f32)?;

    chart.configure_mesh().draw()?;

    chart
        .draw_series(LineSeries::new(
            (-50..=50).map(|x| x as f32 / 50.0).map(|x| (x, x * x)),
            &RED,
        ))?
        .label("y = x^2")
        .legend(|(x, y)| PathElement::new(vec![(x, y)(x + 20, y)]&RED));

    chart
        .configure_series_labels()
        .background_style(&WHITE.mix(0.8))
        .border_style(&BLACK)
        .draw()?;

    root.present()?;

    Ok(())
}

結果如圖:

Gnuplot

Gnuplot 是一個強大的繪圖工具,它有 Rust 的綁定。雖然 Gnuplot 不是特定於 rust 的庫,但它爲創建發佈高質量的圖提供了廣泛的功能。它可以通過命令行接口或 Rust 綁定從 Rust 代碼中調用。

讓我們看一下使用 Gnuplot 畫一個折線圖。

要使用 Gnuplot,想要將 Gnuplot crate 添加到 Cargo.toml 中:

[dependencies]
gnuplot = "0.0.42"

在 main.rs 中,寫入以下代碼:

use gnuplot::{AxesCommon, Caption, Coordinate::Graph, Figure};

fn main() {
    let mut fg = Figure::new();
    fg.set_terminal("png""./gnuplot_test.png");
    fg.axes2d()
        .set_title("A plot"&[])
        .set_legend(Graph(0.5), Graph(0.9)&[]&[])
        .set_x_label("x"&[])
        .set_y_label("y^2"&[])
        .lines(
            [-3., -2., -1., 0., 1., 2., 3.],
            [9., 4., 1., 0., 1., 4., 9.],
            &[Caption("Parabola")],
        );
    fg.show().unwrap();
}

運行後會在項目根目錄下生成 gnuplot_test.png 文件,如圖:

Viskell

Viskell 是一個受 Haskell 庫 Gloss 啓發的可視化庫,用於類型化 (類似 haskell) 的函數式編程語言。它提供了一種在 Rust 中創建交互式可視化的功能方法。雖然仍處於早期開發階段,但 Viskell 展示了構建動態和引人入勝的可視化的前景。

Viskell 的目標和關注點:

總結

強調性能、安全性和併發性的 Rust 可能不是首先想到的數據可視化語言。然而,它的生態系統正在滾雪球般擴大,各種庫和工具不斷湧現,以滿足各種需求,包括數據可視化。通過利用 Rust 的優勢,比如它與其他語言的接口能力和健壯性,我們可以構建高效可靠的數據可視化應用程序。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/sJSDqvLGLSdLjWpFfz9wHA