From 8261bc9c4140e8a97d297e7fc3a675fb81e0de77 Mon Sep 17 00:00:00 2001 From: Jamin Martin Date: Mon, 4 Mar 2024 15:26:00 +1300 Subject: [PATCH] added saving of figures as a new function in evxcr.rs issue #552 --- plotters/src/evcxr.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/plotters/src/evcxr.rs b/plotters/src/evcxr.rs index 921282f3..07401724 100644 --- a/plotters/src/evcxr.rs +++ b/plotters/src/evcxr.rs @@ -2,6 +2,8 @@ use crate::coord::Shift; use crate::drawing::{DrawingArea, IntoDrawingArea}; use plotters_backend::DrawingBackend; use plotters_svg::SVGBackend; +use std::fs::File; +use std::io::Write; #[cfg(feature = "evcxr_bitmap")] #[cfg_attr(doc_cfg, doc(cfg(feature = "evcxr_bitmap")))] @@ -46,6 +48,25 @@ pub fn evcxr_figure< SVGWrapper(buffer, "".to_string()) } +// An evcxr figure that can save to the local file system and render in a notebook. + +pub fn evcxr_figure_with_saving< + Draw: FnOnce(DrawingArea) -> Result<(), Box>, +>( + filename: &str, + size: (u32, u32), + draw: Draw, +) -> SVGWrapper { + let mut buffer = "".to_string(); + let root = SVGBackend::with_string(&mut buffer, size).into_drawing_area(); + draw(root).expect("Drawing failure"); + + let mut file = File::create(filename).expect("Unable to create file"); + file.write_all(buffer.as_bytes()) + .expect("Unable to write data"); + + SVGWrapper(buffer, "".to_string()) +} /// Start drawing an evcxr figure #[cfg(feature = "evcxr_bitmap")] #[cfg_attr(doc_cfg, doc(cfg(feature = "evcxr_bitmap")))]