### Example of Setting Start Angle Source: https://docs.rs/plotters/latest/src/plotters/element/pie.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to set a custom start angle for a Pie chart, for instance, to align it with the vertical Y axis. ```rust use plotters::prelude::*; let mut pie = Pie::new(&(50,50), &10.0, &[50.0, 25.25, 20.0, 5.5], &[RED, BLUE, GREEN, WHITE], &["Red", "Blue", "Green", "White"]); pie.start_angle(-90.0); // retract to a right angle, so it starts aligned to a vertical Y axis. ``` -------------------------------- ### Quick Start: Drawing a Quadratic Function Source: https://docs.rs/plotters/latest/index.html This example demonstrates how to draw a simple quadratic function y=x^2 using the BitMapBackend and Cartesian 2D coordinates. It includes setting up the drawing area, configuring the chart, drawing the mesh, plotting the series, and displaying the legend. ```Rust use plotters::prelude::*; fn main() -> Result<(), Box> { 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, ))?; chart .configure_series_labels() .background_style(&WHITE.mix(0.8)) .border_style(&BLACK) .draw()?; root.present()?; Ok(()) } ``` -------------------------------- ### Area Chart Example Source: https://docs.rs/plotters/latest/src/plotters/lib.rs.html?search= Demonstrates how to create an area chart. This example uses the `plotters` crate. ```rust use plotters::prelude::*; fn main() -> Result<(), Box> { let root = SVGBackend::new("area-chart.svg", (640, 480)).into_drawing_area(); root.fill(&WHITE)?; let mut chart = ChartBuilder::on(&root) .caption("Area Chart", 30.into_font().centered()) .margin(5) .x_label_area_size(30) .y_label_area_size(30) .build_cartesian_2d(0f32..12f32, 0f32..100f32)?; chart.configure_mesh().draw()?; let data = [ (0, 10), (1, 20), (2, 40), (3, 70), (4, 90), (5, 100), (6, 90), (7, 70), (8, 40), (9, 20), (10, 10), (11, 5) ]; chart.draw_series(AreaSeries::new(data, 0, &RED.mix(0.5))) .border_style(RED.stroke_width(2)); root.present()?; Ok(()) } ``` -------------------------------- ### Install Ubuntu Dependencies Source: https://docs.rs/plotters/latest/src/plotters/lib.rs.html?search=std%3A%3Avec Installs necessary packages for Plotters on Ubuntu Linux. ```bash sudo apt install pkg-config libfreetype6-dev libfontconfig1-dev ``` -------------------------------- ### Example Usage of def_linear_colormap Source: https://docs.rs/plotters/latest/plotters/style/colors/colormaps/macro.def_linear_colormap.html?search=u32+-%3E+bool Demonstrates how to use the `def_linear_colormap` macro to create a `BlackWhite` colormap using `RGBColor`. It defines the colormap and asserts its behavior at the start. ```rust use plotters::prelude::*; def_linear_colormap! { BlackWhite, RGBColor, "Simple chromatic colormap from black to white.", ( 0, 0, 0), (255, 255, 255) } assert_eq!(BlackWhite::get_color(0.0), RGBColor(0,0,0)); ``` -------------------------------- ### Draw XOZ Surface Series Example Source: https://docs.rs/plotters/latest/src/plotters/series/surface.rs.html Demonstrates drawing a 3D surface using `SurfaceSeries::xoz`. This example sets up a drawing area, a 3D Cartesian chart, configures axes, adds axis labels, and then draws the surface with a specified style. ```rust use plotters::prelude::*; let drawing_area = SVGBackend::new("surface_series_xoz.svg", (640, 480)).into_drawing_area(); drawing_area.fill(&WHITE).unwrap(); let mut chart_context = ChartBuilder::on(&drawing_area) .margin(10) .build_cartesian_3d(-3.0..3.0f64, -3.0..3.0f64, -3.0..3.0f4) .unwrap(); chart_context.configure_axes().draw().unwrap(); let axis_title_style = ("sans-serif", 20, &BLACK).into_text_style(&drawing_area); chart_context.draw_series([("x", (3., -3., -3.)), ("y", (-3., 3., -3.)), ("z", (-3., -3., 3.))] .map(|(label, position)| Text::new(label, position, &axis_title_style))).unwrap(); chart_context.draw_series(SurfaceSeries::xoz( (-30..30).map(|v| v as f64 / 10.0), (-30..30).map(|v| v as f64 / 10.0), |x:f64,z:f64|(0.7 * (x * x + z * z)).cos()).style(&BLUE.mix(0.5)) ).unwrap(); ``` -------------------------------- ### Basic Plotting Example Source: https://docs.rs/plotters/latest/src/plotters/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E A fundamental example demonstrating how to draw a quadratic function using Plotters. It sets up a drawing area, builds a chart, configures the mesh, draws a line series, and presents the plot. ```rust use plotters::prelude::*; fn main() -> Result<(), Box> { 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(()) } ``` -------------------------------- ### Basic 3D Surface Plot Example Source: https://docs.rs/plotters/latest/plotters/series/struct.SurfaceSeries.html Demonstrates how to create a basic 3D surface plot using SurfaceSeries::xoz. This example sets up a drawing area, a 3D Cartesian chart, configures axes, adds axis labels, and draws the surface. ```rust use plotters::prelude::*; let drawing_area = SVGBackend::new("surface_series_xoz.svg", (640, 480)).into_drawing_area(); drawing_area.fill(&WHITE).unwrap(); let mut chart_context = ChartBuilder::on(&drawing_area) .margin(10) .build_cartesian_3d(-3.0..3.0f64, -3.0..3.0f64, -3.0..3.0f64) .unwrap(); chart_context.configure_axes().draw().unwrap(); let axis_title_style = ("sans-serif", 20, &BLACK).into_text_style(&drawing_area); chart_context.draw_series([("x", (3., -3., -3.)), ("y", (-3., 3., -3.)), ("z", (-3., -3., 3.))] .map(|(label, position)| Text::new(label, position, &axis_title_style))).unwrap(); chart_context.draw_series(SurfaceSeries::xoz( (-30..30).map(|v| v as f64 / 10.0), (-30..30).map(|v| v as f64 / 10.0), |x:f64,z:f64| (0.7 * (x * x + z * z)).cos()).style(&BLUE.mix(0.5)) ).unwrap(); ``` -------------------------------- ### EmptyElement and Composition Source: https://docs.rs/plotters/latest/src/plotters/element/composable.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to start a composition with `EmptyElement` and combine it with other drawable elements like `Circle`, `Cross`, `Pixel`, and `TriangleMarker` using the `+` operator. The example shows creating a single data point that renders multiple shapes. ```APIDOC ## EmptyElement::at ### Description Creates an empty composable element at a specified coordinate. This serves as the starting point for composing multiple drawable elements. ### Method `EmptyElement::at(coord: Coord) -> Self` ### Parameters #### Path Parameters - `coord` (Coord) - The coordinate for the empty element. ### Example ```rust use plotters::prelude::* // Assuming drawing_area and chart_context are already set up let data = [(1.0, 3.3)]; chart_context.draw_series(data.map(|(x, y)| { EmptyElement::at((x, y)) // Start composition at (x, y) + Circle::new((0, 0), 10, BLUE) // Add a circle + Cross::new((4, 4), 3, RED) // Add a cross })).unwrap(); ``` ## Composable Element Addition (`+` operator) ### Description Allows combining `EmptyElement` or `BoxedElement` with other drawable elements using the `+` operator. This creates a `BoxedElement` or `ComposedElement` respectively, enabling the layering of multiple graphical components at a single point. ### Method `impl Add for EmptyElement` `impl Add for BoxedElement` ### Parameters - `other` / `yours` (Other/Yours): The drawable element to compose with the existing element. ### Return Value - `BoxedElement` when adding to `EmptyElement`. - `ComposedElement` when adding to `BoxedElement`. ### Example ```rust use plotters::prelude::* // Assuming drawing_area and chart_context are already set up let point_coord = (2.0, 2.0); // Compose multiple elements starting with EmptyElement let composed_point = EmptyElement::at(point_coord) + Circle::new((0, 0), 5, RED) + TriangleMarker::new((0, 0), 5, GREEN); // Draw the composed element // chart_context.draw_series(once(composed_point)).unwrap(); // Simplified for example ``` ``` -------------------------------- ### Example Usage of GroupBy Combinator Source: https://docs.rs/plotters/latest/src/plotters/coord/ranged1d/combinators/group_by.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to use the `group_by` combinator to create a grouped Cartesian 2D coordinate system. This example sets up a chart with an X-axis that groups values from 0 to 100 into groups of 7. ```rust use plotters::prelude::*; let mut buf = vec![0;1024*768*3]; let area = BitMapBackend::with_buffer(buf.as_mut(), (1024, 768)).into_drawing_area(); let chart = ChartBuilder::on(&area) .build_cartesian_2d((0..100).group_by(7), 0..100) .unwrap(); ``` -------------------------------- ### 3D plot rendering Source: https://docs.rs/plotters/latest/src/plotters/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example demonstrating how to render a 3D plot using Plotters. ```rust use plotters::prelude::*; fn main() -> Result<(), Box> { let root = SVGBackend::new("plotters-doc-data/3d-plot.svg", (640, 480)).into_drawing_area(); root.fill(&WHITE)?; let mut chart = ChartBuilder::on(&root) .caption("3D Plot", ("sans-serif", 50).into_font()) .build_cartesian_3d(0i32..100, 0i32..100, 0i32..100)?; chart.configure_mesh().draw()?; chart.draw_series(PointSeries::of_element( (0..50).map(|x| (x, x, x*x/25)), 5, &RED, &|coord, size, style| { SVGElement::new(coord, size, style) }, ))?; root.present()?; Ok(()) } ``` -------------------------------- ### Setting up Jupyter for Plotters Tutorial Source: https://docs.rs/plotters/latest/index.html Commands to clone the Plotters documentation data repository and start a Jupyter Notebook server for interactive tutorials. ```bash git clone https://github.com/38/plotters-doc-data cd plotters-doc-data jupyter notebook ``` -------------------------------- ### Set Pie Chart Start Angle Source: https://docs.rs/plotters/latest/src/plotters/element/pie.rs.html?search=u32+-%3E+bool Adjusts the starting angle of the first slice in the pie chart. The angle is provided in degrees, with 0.0 aligning to the horizontal axis. For example, -90.0 degrees aligns the start to the vertical Y axis. ```rust use plotters::prelude::* let mut pie = Pie::new(&(50,50), &10.0, &[50.0, 25.25, 20.0, 5.5], &[RED, BLUE, GREEN, WHITE], &["Red", "Blue", "Green", "White"]); pie.start_angle(-90.0); ``` -------------------------------- ### Initialize Bitmap Drawing Backend Source: https://docs.rs/plotters/latest/src/plotters/lib.rs.html?search= Demonstrates how to initialize a bitmap drawing backend for creating image files. Supports other backends like SVG. ```rust use plotters::prelude::* fn main() -> Result<(), Box> { // Create a 800*600 bitmap and start drawing let mut backend = BitMapBackend::new("plotters-doc-data/1.png", (300, 200)); // And if we want SVG backend // let backend = SVGBackend::new("output.svg", (800, 600)); backend.draw_rect((50, 50), (200, 150), &RED, true)?; backend.present()?; Ok(()) } ``` -------------------------------- ### Quartiles Median Retrieval Example Source: https://docs.rs/plotters/latest/src/plotters/data/quartiles.rs.html?search=u32+-%3E+bool Provides a simple method to get only the median value from the calculated quartiles. ```rust /// Get the quartiles median. /// /// - **returns** The median /// /// ```rust /// use plotters::prelude::*; /// /// let quartiles = Quartiles::new(&[7, 15, 36, 39, 40, 41]); /// assert_eq!(quartiles.median(), 37.5); /// ``` pub fn median(&self) -> f64 { self.median } ``` -------------------------------- ### Get Font Style Source: https://docs.rs/plotters/latest/src/plotters/style/text.rs.html Retrieves the current style of the font. No specific setup is required beyond having a font instance. ```rust self.font.get_style() ``` -------------------------------- ### Example Usage of calculate_relative_difference_index_lower_upper Source: https://docs.rs/plotters/latest/src/plotters/style/colors/colormaps.rs.html?search= Demonstrates how to use the `calculate_relative_difference_index_lower_upper` function to get interpolation parameters. Asserts the expected output for a given input. ```rust # use plotters::prelude::* let r = calculate_relative_difference_index_lower_upper(1.2, 1.0, 3.0, 4); let (relative_difference, lower_index, upper_index) = r; assert_eq!(relative_difference, 0.7000000000000001); assert_eq!(lower_index, 0); assert_eq!(upper_index, 1); ``` -------------------------------- ### Create and Configure Pie Chart Source: https://docs.rs/plotters/latest/plotters/element/struct.Pie.html Demonstrates how to create a new Pie object and adjust its starting angle. The `start_angle` method allows for rotation, useful for aligning the pie chart with specific axes. ```Rust use plotters::prelude::* let mut pie = Pie::new(&(50,50), &10.0, &[50.0, 25.25, 20.0, 5.5], &[RED, BLUE, GREEN, WHITE], &["Red", "Blue", "Green", "White"]); pie.start_angle(-90.0); // retract to a right angle, so it starts aligned to a vertical Y axis. ``` -------------------------------- ### Recommended usage of expect for environment variable retrieval Source: https://docs.rs/plotters/latest/plotters/prelude/type.DrawResult.html?search= This example demonstrates a recommended style for `expect` messages, focusing on the expected state of the environment variable. ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### LineSeries Usage Example Source: https://docs.rs/plotters/latest/src/plotters/series/line_series.rs.html?search=u32+-%3E+bool Draws a line series on a Cartesian 2D chart. Requires a drawing area and chart builder setup. ```rust chart .draw_series(LineSeries::new( (0..100).map(|x| (x, x)), Into::::into(RED).stroke_width(3), )) .expect("Drawing Error"); ``` -------------------------------- ### DashedLineSeries Usage Example Source: https://docs.rs/plotters/latest/src/plotters/series/line_series.rs.html?search=u32+-%3E+bool Draws a dashed line series on a Cartesian 2D chart. Requires a drawing area and chart builder setup. ```rust chart .draw_series(DashedLineSeries::new( (0..=50).map(|x| (0, x)), 10, 5, Into::::into(RED).stroke_width(3), )) .expect("Drawing Error"); ``` -------------------------------- ### DottedLineSeries Usage Example Source: https://docs.rs/plotters/latest/src/plotters/series/line_series.rs.html?search=u32+-%3E+bool Draws a dotted line series on a Cartesian 2D chart using a custom marker function. Requires a drawing area and chart builder setup. ```rust let mk_f = |c| Circle::new(c, 3, Into::::into(RED).filled()); chart .draw_series(DottedLineSeries::new((0..=50).map(|x| (x, 0)), 5, 5, mk_f)) .expect("Drawing Error"); ``` -------------------------------- ### Draw a Cubiod in a 3D Chart Source: https://docs.rs/plotters/latest/plotters/element/struct.Cubiod.html Example of creating and drawing a Cubiod in a 3D Cartesian chart using SVG backend. Requires plotters prelude and specific backend setup. ```rust use plotters::prelude::*; let drawing_area = SVGBackend::new("cuboid.svg", (300, 200)).into_drawing_area(); drawing_area.fill(&WHITE).unwrap(); let mut chart_builder = ChartBuilder::on(&drawing_area); let mut chart_context = chart_builder.margin(20).build_cartesian_3d(0.0..3.5, 0.0..2.5, 0.0..1.5).unwrap(); chart_context.configure_axes().x_labels(4).y_labels(3).z_labels(2).draw().unwrap(); let cubiod = Cubiod::new([(0.,0.,0.), (3.,2.,1.)], BLUE.mix(0.2), BLUE); chart_context.draw_series(std::iter::once(cubiod)).unwrap(); ``` -------------------------------- ### Building and Configuring a 2D Cartesian Chart Source: https://docs.rs/plotters/latest/src/plotters/chart/context.rs.html?search= Demonstrates the setup of a 2D Cartesian chart, including setting captions, label area sizes, and defining the coordinate system. It also shows how to configure and draw mesh lines with axis descriptions. ```rust let mut chart = ChartBuilder::on(&drawing_area) .caption("Test Title", ("serif", 10)) .x_label_area_size(20) .y_label_area_size(20) .set_label_area_size(LabelAreaPosition::Top, 20) .set_label_area_size(LabelAreaPosition::Right, 20) .build_cartesian_2d(0..10, 0..10) .expect("Create chart") .set_secondary_coord(0.0..1.0, 0.0..1.0); chart .configure_mesh() .x_desc("X") .y_desc("Y") .draw() .expect("Draw mesh"); chart .configure_secondary_axes() .x_desc("X") .y_desc("Y") .draw() .expect("Draw Secondary axes"); ``` -------------------------------- ### Create and Configure a 3D Cartesian Chart Source: https://docs.rs/plotters/latest/src/plotters/chart/context.rs.html?search=std%3A%3Avec Shows how to build a 3D Cartesian chart and set its projection parameters like yaw, pitch, and scale. ```rust let drawing_area = create_mocked_drawing_area(200, 200, |_| {}); drawing_area.fill(&WHITE).expect("Fill"); let mut chart = ChartBuilder::on(&drawing_area) .caption("Test Title", ("serif", 10)) .x_label_area_size(20) .y_label_area_size(20) .set_label_area_size(LabelAreaPosition::Top, 20) .set_label_area_size(LabelAreaPosition::Right, 20) .build_cartesian_3d(0..10, 0..10, 0..10) .expect("Create chart"); chart.with_projection(|mut pb| { pb.yaw = 0.5; pb.pitch = 0.5; pb.scale = 0.5; pb.into_matrix() }); ``` -------------------------------- ### Create FontDesc with Color Source: https://docs.rs/plotters/latest/plotters/style/struct.FontDesc.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to create a TextStyle with a specific color using FontDesc. Requires importing prelude and a drawing backend. ```rust use plotters::prelude::*; let text_style = ("sans-serif", 20).into_font().color(&RED); let drawing_area = SVGBackend::new("font_desc_color.svg", (200, 100)).into_drawing_area(); drawing_area.fill(&WHITE).unwrap(); drawing_area.draw_text("This is a big red label", &text_style, (10, 50)); ``` -------------------------------- ### Pie Chart Calculations and Initialization Source: https://docs.rs/plotters/latest/src/plotters/element/pie.rs.html Demonstrates the initialization of a Pie chart and verifies its total calculation. It also shows that the Pie struct is not ownership greedy. ```rust let mut center = (5, 5); let mut radius = 800.0; let sizes = vec![50.0, 25.0]; // length isn't validated in new() let colors = vec![]; let labels: Vec<&str> = vec![]; let pie = Pie::new(¢er, &radius, &sizes, &colors, &labels); assert_eq!(pie.total, 75.0); // total calculated from sizes // not ownership greedy center.1 += 1; radius += 1.0; assert!(colors.get(0).is_none()); assert!(labels.first().is_none()); assert_eq!(radius, 801.0); ``` -------------------------------- ### Get Font Name Source: https://docs.rs/plotters/latest/src/plotters/style/font/font_desc.rs.html?search= Use `FontDesc::get_name` to get the string name of the font family. ```rust pub fn get_name(&self) -> &str { self.family.as_str() } ``` -------------------------------- ### Pie Chart Creation Source: https://docs.rs/plotters/latest/src/plotters/element/pie.rs.html?search= Demonstrates how to create a new Pie chart instance with essential parameters like center, radius, sizes, colors, and labels. ```APIDOC ## Pie::new ### Description Build a Pie object. Assumes a start angle at 0.0, which is aligned to the horizontal axis. ### Parameters - `center`: A reference to the center coordinates of the pie chart `&(i32, i32)`. - `radius`: A reference to the radius of the pie chart `&f64`. - `sizes`: A slice of `f64` representing the size of each wedge. - `colors`: A slice of `RGBColor` for each wedge. - `labels`: A slice of labels for each wedge, where each label must implement `Display`. ### Returns - `Self`: A new `Pie` instance. ### Example ```rust use plotters::prelude::* let sizes = [50.0, 25.25, 20.0, 5.5]; let colors = [RED, BLUE, GREEN, WHITE]; let labels = ["Red", "Blue", "Green", "White"]; let mut pie = Pie::new(&(50, 50), &10.0, &sizes, &colors, &labels); ``` ``` -------------------------------- ### 1D Gaussian Distribution Example Source: https://docs.rs/plotters/latest/src/plotters/lib.rs.html Visualizes a 1D Gaussian (normal) distribution. This is a fundamental example for statistical plotting. ```rust use plotters::prelude::* fn main() -> Result<(), Box> { let root = BitMapBackend::new("normal-dist2.png", (600, 400)).into_drawing_area(); root.fill(&WHITE)?; let mut chart = ChartBuilder::on(&root) .caption("1D Gaussian Distribution", EmptyElement) .margin(5) .x_label_area_size(30) .y_label_area_size(30) .build_cartesian_2d(-3.0..3.0, 0.0..0.5)?; chart.configure_mesh().draw()?; let data: Vec<(f64, f64)> = (-150..=150) .map(|x| { let x = x as f64 / 50.0; (x, (-(x.powi(2)) / 2.0).exp() / (2.0 * std::f64::consts::PI).sqrt()) // Gaussian PDF }) .collect(); chart.draw_series(LineSeries::new(data, &BLUE))?; root.present()?; Ok(()) } ``` -------------------------------- ### Get Color from DerivedColorMap Source: https://docs.rs/plotters/latest/plotters/style/struct.RGBAColor.html?search=std%3A%3Avec Gets a color from a DerivedColorMap based on a normalized scalar value (0.0 to 1.0). ```rust fn get_color(&self, h: FloatType) -> ColorType; ``` -------------------------------- ### Create an in-memory BitMapBackend with specific format Source: https://docs.rs/plotters/latest/plotters/prelude/struct.BitMapBackend.html Creates a bitmap backend using a provided buffer and a specific pixel format. This offers more flexibility than `with_buffer`. ```rust pub fn with_buffer_and_format( buf: &'a mut [u8], _: (u32, u32), ) -> Result, BitMapBackendError> where P: PixelFormat, ``` -------------------------------- ### Get Color Normalized from DerivedColorMap Source: https://docs.rs/plotters/latest/plotters/style/struct.RGBAColor.html?search=std%3A%3Avec Gets a color from a DerivedColorMap normalized between specified min and max values. ```rust fn get_color_normalized( &self, h: FloatType, min: FloatType, max: FloatType, ) -> RGBAColor; ``` -------------------------------- ### Drawing a Rectangle with BitMapBackend Source: https://docs.rs/plotters/latest/index.html Example of creating a bitmap drawing backend and drawing a red rectangle on it. The `present()` method is called to finalize the drawing. ```rust use plotters::prelude::*; fn main() -> Result<(), Box> { // Create a 800*600 bitmap and start drawing let mut backend = BitMapBackend::new("plotters-doc-data/1.png", (300, 200)); // And if we want SVG backend // let backend = SVGBackend::new("output.svg", (800, 600)); backend.draw_rect((50, 50), (200, 150), &RED, true)?; backend.present()?; Ok(()) } ``` -------------------------------- ### Error Bar Plot Example Source: https://docs.rs/plotters/latest/src/plotters/lib.rs.html?search= Demonstrates how to create a plot with error bars. This example uses the `plotters` crate. ```rust use plotters::prelude::*; fn main() -> Result<(), Box> { let root = SVGBackend::new("errorbar.svg", (640, 480)).into_drawing_area(); root.fill(&WHITE)?; let mut chart = ChartBuilder::on(&root) .caption("Error Bar Example", 30.into_font().centered()) .margin(5) .x_label_area_size(30) .y_label_area_size(30) .build_cartesian_2d(0f32..10f32, 0f32..100f32)?; chart.configure_mesh().draw()?; let data = [ (1, 50, 10), (2, 60, 15), (3, 70, 12), (4, 80, 18), (5, 90, 14), (6, 85, 16), (7, 75, 13), (8, 65, 11), (9, 55, 9), ]; chart.draw_series(data.iter().map(|(x, y, err)| { ErrorBar::new_vertical(*x, *y, *err, 5.0, RED.stroke_width(2)) }))?; root.present()?; Ok(()) } ``` -------------------------------- ### DerivedColorMap Example Source: https://docs.rs/plotters/latest/src/plotters/style/colors/colormaps.rs.html?search= Demonstrates creating a DerivedColorMap with BLACK, BLUE, and WHITE, and testing its color retrieval at different scalar values. ```rust use plotters::prelude::{BLACK,BLUE,WHITE,DerivedColorMap,ColorMap}; let derived_colormap = DerivedColorMap::new( &[BLACK, BLUE, WHITE] ); assert_eq!(derived_colormap.get_color(0.0), BLACK); assert_eq!(derived_colormap.get_color(0.5), BLUE); assert_eq!(derived_colormap.get_color(1.0), WHITE); ``` -------------------------------- ### CPU Usage Statistics Plot Source: https://docs.rs/plotters/latest/src/plotters/lib.rs.html?search= Example of plotting CPU usage statistics. This snippet is part of the plotters-piston examples. ```rust /* * Copyright 2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * * You may not use this file except in compliance with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. */ use plotters::prelude::* use plotters_piston::prelude::* const COLOR_1: RGBColor = RGBColor(0, 0, 255); const COLOR_2: RGBColor = RGBColor(255, 0, 0); const COLOR_3: RGBColor = RGBColor(0, 255, 0); fn main() -> Result<(), Box> { let mut chart = ChartBuilder::on_root_area_size(1024, 768)? .caption("CPU Stat", 50.into_font().centered()) .margin(20) .x_label_area_size(40) .y_label_area_size(40) .build_cartesian_2d(0u32..100, 0f32..100f32)?; chart .configure_mesh() .x_desc("Time") .y_desc("Usage") .draw()?; let mut data = Vec::new(); let mut count = 0; chart.draw_series(LineSeries::new( (0..100).map(|x| { let y = (x as f32 / 100.0) * 100.0; data.push(y); (x, y) }), &COLOR_1, ))?; chart.draw_series(LineSeries::new( (0..100).map(|x| { let y = (x as f32 / 100.0) * 100.0; data.push(y); (x, y) }), &COLOR_2, ))?; chart.draw_series(LineSeries::new( (0..100).map(|x| { let y = (x as f32 / 100.0) * 100.0; data.push(y); (x, y) }), &COLOR_3, ))?; Ok(()) } ``` -------------------------------- ### Create and Configure ChartBuilder Source: https://docs.rs/plotters/latest/plotters/chart/struct.ChartBuilder.html?search= Demonstrates how to create a ChartBuilder on a drawing area, set margins, label area sizes, and a caption, then build a Cartesian 2D chart with a mesh. This is useful for initializing a chart with specific visual properties. ```rust use plotters::prelude::*; let drawing_area = SVGBackend::new("chart_builder_on.svg", (300, 200)).into_drawing_area(); drawing_area.fill(&WHITE).unwrap(); let mut chart_builder = ChartBuilder::on(&drawing_area); chart_builder.margin(5).set_left_and_bottom_label_area_size(35) .caption("Figure title or caption", ("Calibri", 20, FontStyle::Italic, &RED).into_text_style(&drawing_area)); let mut chart_context = chart_builder.build_cartesian_2d(0.0..3.8, 0.0..2.8).unwrap(); chart_context.configure_mesh().draw().unwrap(); ``` -------------------------------- ### Koch Snowflake Animation Example Source: https://docs.rs/plotters/latest/src/plotters/lib.rs.html Generates an animation of the Koch snowflake fractal. This example showcases dynamic drawing and frame-by-frame rendering. ```rust use plotters::prelude::* const OUT_SIZE: (u32, u32) = (800, 800); fn koch(p1: Point, p2: Point, level: u32, path: &mut Vec, color: RGBAColor) { if level == 0 { path.push(PathElement::new(vec![p1, p2], color.stroke_width(1))); } else { let p3 = p1.lerp_by(p2, 1.0 / 3.0); let p4 = p1.lerp_by(p2, 2.0 / 3.0); let p5 = p3.lerp_by(p4, 0.5).offset((p4.y - p3.y) * 0.866, -(p4.x - p3.x) * 0.866); koch(p1, p3, level - 1, path, color); koch(p3, p5, level - 1, path, color); koch(p5, p4, level - 1, path, color); koch(p4, p2, level - 1, path, color); } } fn main() -> Result<(), Box> { let root = GifBackend::new("animation.gif", 100, (800, 800)).into_drawing_area(); root.fill(&WHITE)?; let mut chart = ChartBuilder::on(&root) .caption("Koch Snowflake Animation", EmptyElement) .margin(10) .build_cartesian_2d(0.0..OUT_SIZE.0 as f64, 0.0..OUT_SIZE.1 as f64)?; chart.configure_mesh().draw()?; for i in 0..5 { let mut path = Vec::new(); let p1 = Point::new(OUT_SIZE.0 as f64 / 2.0, 50.0); let p2 = Point::new(50.0, OUT_SIZE.1 as f64 - 50.0); let p3 = Point::new(OUT_SIZE.0 as f64 - 50.0, OUT_SIZE.1 as f64 - 50.0); koch(p1, p2, i, &mut path, &BLUE); koch(p2, p3, i, &mut path, &BLUE); koch(p3, p1, i, &mut path, &BLUE); chart.draw_series(path.into_iter())?; root.update()?; } Ok(()) } ``` -------------------------------- ### Option Mapping Example Source: https://docs.rs/plotters/latest/src/plotters/chart/context/cartesian2d/draw_impl.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to map a function over an Option to produce an Option. This is useful for applying transformations to values that may or may not be present. ```rust if y_axis { Some(axis_style) } else { None }, &y_labels[..], y_label_style, y_label_offset, (-1 + idx as i16 * 2, 0), y_desc.as_ref().map(|desc| (&desc[..], axis_desc_style)), y_tick_size[idx], ?; } Ok(()) } ``` -------------------------------- ### Koch Snowflake Fractal Example Source: https://docs.rs/plotters/latest/src/plotters/lib.rs.html Generates a Koch snowflake fractal. This example demonstrates recursive drawing and geometric pattern generation. ```rust use plotters::prelude::* const OUT_SIZE: (u32, u32) = (800, 800); fn koch(p1: Point, p2: Point, level: u32, path: &mut Vec, color: RGBAColor) { if level == 0 { path.push(PathElement::new(vec![p1, p2], color.stroke_width(1))); } else { let p3 = p1.lerp_by(p2, 1.0 / 3.0); let p4 = p1.lerp_by(p2, 2.0 / 3.0); let p5 = p3.lerp_by(p4, 0.5).offset((p4.y - p3.y) * 0.866, -(p4.x - p3.x) * 0.866); koch(p1, p3, level - 1, path, color); koch(p3, p5, level - 1, path, color); koch(p5, p4, level - 1, path, color); koch(p4, p2, level - 1, path, color); } } fn main() -> Result<(), Box> { let root = BitMapBackend::new("snowflake.png", OUT_SIZE).into_drawing_area(); root.fill(&WHITE)?; let mut chart = ChartBuilder::on(&root) .caption("Koch Snowflake", EmptyElement) .margin(10) .build_cartesian_2d(0.0..OUT_SIZE.0 as f64, 0.0..OUT_SIZE.1 as f64)?; chart.configure_mesh().draw()?; let mut path = Vec::new(); let p1 = Point::new(OUT_SIZE.0 as f64 / 2.0, 50.0); let p2 = Point::new(50.0, OUT_SIZE.1 as f64 - 50.0); let p3 = Point::new(OUT_SIZE.0 as f64 - 50.0, OUT_SIZE.1 as f64 - 50.0); koch(p1, p2, 4, &mut path, &BLUE); koch(p2, p3, 4, &mut path, &BLUE); koch(p3, p1, 4, &mut path, &BLUE); chart.draw_series(path.into_iter())?; root.present()?; Ok(()) } ``` -------------------------------- ### Drawing on a Console Example Source: https://docs.rs/plotters/latest/src/plotters/lib.rs.html Demonstrates how to draw graphics directly onto a console or terminal. This is useful for simple visualizations in text-based environments. ```rust use plotters::prelude::* fn main() -> Result<(), Box> { let root = SVGBackend::new("console.png", (600, 400)).into_drawing_area(); root.fill(&WHITE)?; let mut chart = ChartBuilder::on(&root) .caption("Drawing on Console", EmptyElement) .margin(5) .x_label_area_size(30) .y_label_area_size(30) .build_cartesian_2d(0..10, 0..10)?; chart.configure_mesh().draw()?; chart.draw_series(PointSeries::outliers(vec![(2, 3), (5, 7), (8, 4)], 5, &RED))?; root.present()?; Ok(()) } ``` -------------------------------- ### Basic Plotting Example Source: https://docs.rs/plotters/latest/src/plotters/lib.rs.html?search=std%3A%3Avec Draws a quadratic function y=x^2 on a bitmap image. Requires the BitMapBackend and Cartesian 2D chart. ```rust use plotters::prelude::*; fn main() -> Result<(), Box> { 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(()) } ``` -------------------------------- ### Histogram Example Source: https://docs.rs/plotters/latest/src/plotters/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides an example of generating a histogram, a graphical representation of the distribution of numerical data. Refer to the linked code for details. ```rust https://github.com/plotters-rs/plotters/blob/master/plotters/examples/histogram.rs ``` -------------------------------- ### Setting up Chart Context with Margins Source: https://docs.rs/plotters/latest/src/plotters/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes a drawing area and applies margins, preparing it for further chart elements. This is a prerequisite for drawing more complex charts with labels and data series. ```rust use plotters::prelude::*; fn main() -> Result<(), Box> { let root = BitMapBackend::new("plotters-doc-data/5.png", (640, 480)).into_drawing_area(); root.fill(&WHITE); let root = root.margin(10, 10, 10, 10); } ``` -------------------------------- ### FromIterator Example: Failed Collection Source: https://docs.rs/plotters/latest/plotters/style/type.FontResult.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates using `collect` with an iterator of Results. This example shows a failed collection where an Err is encountered, and the iteration stops. ```rust let v = vec![1, 2, 0]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_sub(1).ok_or("Underflow!") ).collect(); assert_eq!(res, Err("Underflow!")); ``` -------------------------------- ### BindKeyPoints Example Source: https://docs.rs/plotters/latest/plotters/coord/types/struct.RangedSlice.html?search=std%3A%3Avec Shows how to bind a predefined vector of key points to a coordinate specification using the BindKeyPoints trait. ```rust impl BindKeyPoints for T where T: AsRangedCoord, { fn with_key_points( self, points: Vec, ) -> WithKeyPoints { // ... } } ``` -------------------------------- ### Histogram with Scatter Plot Example Source: https://docs.rs/plotters/latest/src/plotters/lib.rs.html Demonstrates how to create a histogram combined with a scatter plot. This example is useful for visualizing data distributions and individual data points simultaneously. ```rust use plotters::prelude::* fn main() -> Result<(), Box> { let root = BitMapBackend::new("normal-dist.png", (600, 400)).into_drawing_area(); root.fill(&WHITE)?; let mut chart = ChartBuilder::on(&root) .caption("Histogram with Scatter", EmptyElement) .margin(5) .x_label_area_size(30) .y_label_area_size(30) .build_cartesian_2d(-0.5..3.5, 0.0..1.0)?; chart.configure_mesh().draw()?; let data = [ (0, 0.1), (0, 0.5), (1, 0.3), (1, 0.6), (1, 0.8), (2, 0.2), (2, 0.7), (3, 0.4) ]; chart.draw_series(Histogram::vertical(data.iter().map(|(x, y)| (*x, *y))))?; chart.draw_series(PointSeries::outliers(data.iter().map(|(x, y)| (*x, *y)), 5, &RED))?; root.present()?; Ok(()) } ``` -------------------------------- ### FromIterator Example: Successful Collection Source: https://docs.rs/plotters/latest/plotters/style/type.FontResult.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates using `collect` with an iterator of Results to create a Result containing a collection. This example shows a successful collection where all elements are Ok. ```rust let v = vec![1, 2]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_add(1).ok_or("Overflow!") ).collect(); assert_eq!(res, Ok(vec![2, 3])); ``` -------------------------------- ### Convert f64 to TextStyle Source: https://docs.rs/plotters/latest/src/plotters/style/text.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to create a `TextStyle` with a SansSerif font and a font size specified by an `f64`. ```rust impl IntoTextStyle<'static> for f64 { fn into_text_style(self, _: &P) -> TextStyle<'static> { TextStyle::from((FontFamily::SansSerif, self)) } } ```