alceal / plotlars

Plotlars is a Rust library designed to facilitate the integration between the Polars data analysis library and Plotly library.
https://docs.rs/plotlars
MIT License
264 stars 5 forks source link

[Feature Request] Add Plot -> JSON output #27

Closed matthewalltop closed 2 weeks ago

matthewalltop commented 2 weeks ago

Thank you for making this crate - I've greatly enjoyed using it.

I have been using the .to_json() methods exposed from the Plot trait to build a JSON API payload for a web application using the Plot layout + traces - I noticed this is now inaccessible in the latest version of the crate - looks like a change from #26 .

Could you add a .to_json() method that can be called off of .build() for each plot & output a serialized JSON payload of the plot?

I have been doing it similarly to this:

use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct PlotlyPlot {
    pub(crate) layout: String,
    pub(crate) traces: Vec<String>
}

// Example Plot Type
let plots = BarPlot::builder()/**/.build();

// Layout
let layout = plots.get_layout().to_json();

// Traces
let traces: Vec<String> = plots.get_traces().into_iter().map(|x| x.as_ref().to_json()).collect();

// Serialize
let response = PlotlyGraph { layout, traces };
let json = serde_json::to_string(&response);

i.e.

let response = BarPlot::builder()
             /** */
             .build()
             .to_json();

That can be plugged into the PlotlyJS component in custom web applications:

<plotly-plot [layout]="plot.layout" [data]="plot.traces"></plotly-plot>
alceal commented 2 weeks ago

@matthewalltop Thank you for using this crate and for contribute with an idea to improve it. I've published the version 0.7.1. The plots have the to_json method.