Skip to main content

BoxPlot

Struct BoxPlot 

Source
pub struct BoxPlot { /* private fields */ }
Expand description

A structure representing a box plot.

The BoxPlot struct facilitates the creation and customization of box plots with various options for data selection, layout configuration, and aesthetic adjustments. It supports both horizontal and vertical orientations, grouping of data, display of individual data points with jitter and offset, opacity settings, and customizable markers and colors.

§Arguments

  • data - A reference to the DataFrame containing the data to be plotted.
  • labels - A string slice specifying the column name to be used for the x-axis (independent variable).
  • values - A string slice specifying the column name to be used for the y-axis (dependent variable).
  • orientation - An optional Orientation enum specifying whether the plot should be horizontal or vertical.
  • group - An optional string slice specifying the column name to be used for grouping data points.
  • sort_groups_by - Optional comparator fn(&str, &str) -> std::cmp::Ordering to control group ordering. Groups are sorted lexically by default.
  • facet - An optional string slice specifying the column name to be used for creating facets (small multiples).
  • facet_config - An optional reference to a FacetConfig struct for customizing facet layout and behavior.
  • box_points - An optional boolean indicating whether individual data points should be plotted along with the box plot.
  • point_offset - An optional f64 value specifying the horizontal offset for individual data points when box_points is enabled.
  • jitter - An optional f64 value indicating the amount of jitter (random noise) to apply to individual data points for visibility.
  • opacity - An optional f64 value specifying the opacity of the plot markers (range: 0.0 to 1.0).
  • color - An optional Rgb value specifying the color of the markers to be used for the plot. This is used when group is not specified.
  • colors - An optional vector of Rgb values specifying the colors to be used for the plot. This is used when group is specified to differentiate between groups.
  • plot_title - An optional Text struct specifying the title of the plot.
  • x_title - An optional Text struct specifying the title of the x-axis.
  • y_title - An optional Text struct specifying the title of the y-axis.
  • legend_title - An optional Text struct specifying the title of the legend.
  • x_axis - An optional reference to an Axis struct for customizing the x-axis.
  • y_axis - An optional reference to an Axis struct for customizing the y-axis.
  • legend - An optional reference to a Legend struct for customizing the legend of the plot (e.g., positioning, font, etc.).

§Example

use plotlars::{Axis, BoxPlot, Legend, Orientation, Plot, Rgb, Text};
use polars::prelude::*;

let dataset = LazyCsvReader::new(PlRefPath::new("data/penguins.csv"))
    .finish()
    .unwrap()
    .select([
        col("species"),
        col("sex").alias("gender"),
        col("flipper_length_mm").cast(DataType::Int16),
        col("body_mass_g").cast(DataType::Int16),
    ])
    .collect()
    .unwrap();

BoxPlot::builder()
    .data(&dataset)
    .labels("species")
    .values("body_mass_g")
    .orientation(Orientation::Vertical)
    .group("gender")
    .box_points(true)
    .point_offset(-1.5)
    .jitter(0.01)
    .opacity(0.1)
    .colors(vec![
        Rgb(0, 191, 255),
        Rgb(57, 255, 20),
        Rgb(255, 105, 180),
    ])
    .plot_title(
        Text::from("Box Plot")
            .font("Arial")
            .size(18)
    )
    .x_title(
        Text::from("species")
            .font("Arial")
            .size(15)
    )
    .y_title(
        Text::from("body mass (g)")
            .font("Arial")
            .size(15)
    )
    .legend_title(
        Text::from("gender")
            .font("Arial")
            .size(15)
    )
    .y_axis(
        &Axis::new()
            .value_thousands(true)
    )
    .legend(
        &Legend::new()
            .border_width(1)
            .x(0.9)
    )
    .build()
    .plot();

Example

Implementations§

Source§

impl BoxPlot

Source

pub fn builder<'f1, 'f2, 'f3, 'f4, 'f5, 'f6, 'f7, 'f8, 'f9>() -> BoxPlotBuilder<'f1, 'f2, 'f3, 'f4, 'f5, 'f6, 'f7, 'f8, 'f9>

Examples found in repository?
examples/faceting.rs (line 62)
49fn boxplot_example() {
50    let dataset = LazyCsvReader::new(PlRefPath::new("data/penguins.csv"))
51        .finish()
52        .unwrap()
53        .select([
54            col("species"),
55            col("island"),
56            col("sex"),
57            col("body_mass_g").cast(DataType::Int16),
58        ])
59        .collect()
60        .unwrap();
61
62    BoxPlot::builder()
63        .data(&dataset)
64        .labels("island")
65        .values("body_mass_g")
66        .group("sex")
67        .colors(vec![Rgb(0, 119, 182), Rgb(0, 180, 216), Rgb(144, 224, 239)])
68        .facet("species")
69        .facet_config(&FacetConfig::new().cols(3))
70        .plot_title(Text::from("Body Mass by Island, Sex and Species").size(16))
71        .x_title(Text::from("Island"))
72        .y_title(Text::from("Body Mass (g)"))
73        .legend_title(Text::from("Sex"))
74        .build()
75        .plot();
76}
More examples
Hide additional examples
examples/boxplot.rs (line 17)
4fn main() {
5    let dataset = LazyCsvReader::new(PlRefPath::new("data/penguins.csv"))
6        .finish()
7        .unwrap()
8        .select([
9            col("species"),
10            col("sex").alias("gender"),
11            col("flipper_length_mm").cast(DataType::Int16),
12            col("body_mass_g").cast(DataType::Int16),
13        ])
14        .collect()
15        .unwrap();
16
17    BoxPlot::builder()
18        .data(&dataset)
19        .labels("species")
20        .values("body_mass_g")
21        .orientation(Orientation::Vertical)
22        .group("gender")
23        .box_points(true)
24        .point_offset(-1.5)
25        .jitter(0.01)
26        .opacity(0.1)
27        .colors(vec![Rgb(0, 191, 255), Rgb(57, 255, 20), Rgb(255, 105, 180)])
28        .plot_title(Text::from("Box Plot").font("Arial").size(18))
29        .x_title(Text::from("species").font("Arial").size(15))
30        .y_title(Text::from("body mass (g)").font("Arial").size(15).x(-0.04))
31        .legend_title(Text::from("gender").font("Arial").size(15))
32        .y_axis(&Axis::new().value_thousands(true))
33        .legend(&Legend::new().border_width(1).x(0.9))
34        .build()
35        .plot();
36}
examples/subplot_grid.rs (line 109)
15fn regular_grid_example() {
16    let dataset1 = LazyCsvReader::new(PlRefPath::new("data/animal_statistics.csv"))
17        .finish()
18        .unwrap()
19        .collect()
20        .unwrap();
21
22    let plot1 = BarPlot::builder()
23        .data(&dataset1)
24        .labels("animal")
25        .values("value")
26        .orientation(Orientation::Vertical)
27        .group("gender")
28        .sort_groups_by(|a, b| a.len().cmp(&b.len()))
29        .error("error")
30        .colors(vec![Rgb(255, 127, 80), Rgb(64, 224, 208)])
31        .plot_title(Text::from("Bar Plot").x(-0.05).y(1.35).size(14))
32        .y_title(Text::from("value").x(-0.055).y(0.76))
33        .x_title(Text::from("animal").x(0.97).y(-0.2))
34        .legend(
35            &Legend::new()
36                .orientation(Orientation::Horizontal)
37                .x(0.4)
38                .y(1.2),
39        )
40        .build();
41
42    let dataset2 = LazyCsvReader::new(PlRefPath::new("data/penguins.csv"))
43        .finish()
44        .unwrap()
45        .select([
46            col("species"),
47            col("sex").alias("gender"),
48            col("flipper_length_mm").cast(DataType::Int16),
49            col("body_mass_g").cast(DataType::Int16),
50        ])
51        .collect()
52        .unwrap();
53
54    let axis = Axis::new()
55        .show_line(true)
56        .tick_direction(TickDirection::OutSide)
57        .value_thousands(true);
58
59    let plot2 = ScatterPlot::builder()
60        .data(&dataset2)
61        .x("body_mass_g")
62        .y("flipper_length_mm")
63        .group("species")
64        .sort_groups_by(|a, b| {
65            if a.len() == b.len() {
66                a.cmp(b)
67            } else {
68                a.len().cmp(&b.len())
69            }
70        })
71        .opacity(0.5)
72        .size(12)
73        .colors(vec![Rgb(178, 34, 34), Rgb(65, 105, 225), Rgb(255, 140, 0)])
74        .shapes(vec![Shape::Circle, Shape::Square, Shape::Diamond])
75        .plot_title(Text::from("Scatter Plot").x(-0.075).y(1.35).size(14))
76        .x_title(Text::from("body mass (g)").y(-0.4))
77        .y_title(Text::from("flipper length (mm)").x(-0.078).y(0.5))
78        .legend_title("species")
79        .x_axis(&axis.clone().value_range(vec![2500.0, 6500.0]))
80        .y_axis(&axis.clone().value_range(vec![170.0, 240.0]))
81        .legend(&Legend::new().x(0.98).y(0.95))
82        .build();
83
84    let dataset3 = LazyCsvReader::new(PlRefPath::new("data/debilt_2023_temps.csv"))
85        .with_has_header(true)
86        .with_try_parse_dates(true)
87        .finish()
88        .unwrap()
89        .with_columns(vec![
90            (col("tavg") / lit(10)).alias("avg"),
91            (col("tmin") / lit(10)).alias("min"),
92            (col("tmax") / lit(10)).alias("max"),
93        ])
94        .collect()
95        .unwrap();
96
97    let plot3 = TimeSeriesPlot::builder()
98        .data(&dataset3)
99        .x("date")
100        .y("avg")
101        .additional_series(vec!["min", "max"])
102        .colors(vec![Rgb(128, 128, 128), Rgb(0, 122, 255), Rgb(255, 128, 0)])
103        .lines(vec![Line::Solid, Line::Dot, Line::Dot])
104        .plot_title(Text::from("Time Series Plot").x(-0.05).y(1.35).size(14))
105        .y_title(Text::from("temperature (ºC)").x(-0.055).y(0.6))
106        .legend(&Legend::new().x(0.9).y(1.25))
107        .build();
108
109    let plot4 = BoxPlot::builder()
110        .data(&dataset2)
111        .labels("species")
112        .values("body_mass_g")
113        .orientation(Orientation::Vertical)
114        .group("gender")
115        .box_points(true)
116        .point_offset(-1.5)
117        .jitter(0.01)
118        .opacity(0.1)
119        .colors(vec![Rgb(0, 191, 255), Rgb(57, 255, 20), Rgb(255, 105, 180)])
120        .plot_title(Text::from("Box Plot").x(-0.075).y(1.35).size(14))
121        .x_title(Text::from("species").y(-0.3))
122        .y_title(Text::from("body mass (g)").x(-0.08).y(0.5))
123        .legend_title(Text::from("gender").size(12))
124        .y_axis(&Axis::new().value_thousands(true))
125        .legend(&Legend::new().x(1.0))
126        .build();
127
128    SubplotGrid::regular()
129        .plots(vec![&plot1, &plot2, &plot3, &plot4])
130        .rows(2)
131        .cols(2)
132        .v_gap(0.4)
133        .title(
134            Text::from("Regular Subplot Grid")
135                .size(16)
136                .font("Arial bold")
137                .y(0.95),
138        )
139        .build()
140        .plot();
141}
examples/dimensions.rs (line 107)
7fn main() {
8    let penguins_dataset = LazyCsvReader::new(PlRefPath::new("data/penguins.csv"))
9        .finish()
10        .unwrap()
11        .select([
12            col("species"),
13            col("sex").alias("gender"),
14            col("flipper_length_mm").cast(DataType::Int16),
15            col("body_mass_g").cast(DataType::Int16),
16        ])
17        .collect()
18        .unwrap();
19
20    let temperature_dataset = LazyCsvReader::new(PlRefPath::new("data/debilt_2023_temps.csv"))
21        .with_has_header(true)
22        .with_try_parse_dates(true)
23        .finish()
24        .unwrap()
25        .with_columns(vec![
26            (col("tavg") / lit(10)).alias("tavg"),
27            (col("tmin") / lit(10)).alias("tmin"),
28            (col("tmax") / lit(10)).alias("tmax"),
29        ])
30        .collect()
31        .unwrap();
32
33    let animals_dataset = LazyCsvReader::new(PlRefPath::new("data/animal_statistics.csv"))
34        .finish()
35        .unwrap()
36        .collect()
37        .unwrap();
38
39    let axis = Axis::new()
40        .show_line(true)
41        .tick_direction(TickDirection::OutSide)
42        .value_thousands(true);
43
44    let plot1 = TimeSeriesPlot::builder()
45        .data(&temperature_dataset)
46        .x("date")
47        .y("tavg")
48        .additional_series(vec!["tmin", "tmax"])
49        .colors(vec![Rgb(128, 128, 128), Rgb(0, 122, 255), Rgb(255, 128, 0)])
50        .lines(vec![Line::Solid, Line::Dot, Line::Dot])
51        .plot_title(
52            Text::from("De Bilt Temperature 2023")
53                .font("Arial Bold")
54                .size(16),
55        )
56        .y_title(Text::from("temperature (°C)").size(13).x(-0.08))
57        // .legend_title(Text::from("Measure").size(12))
58        .legend(&Legend::new().x(0.1).y(0.9))
59        .build();
60
61    let plot2 = ScatterPlot::builder()
62        .data(&penguins_dataset)
63        .x("body_mass_g")
64        .y("flipper_length_mm")
65        .group("species")
66        .sort_groups_by(|a, b| {
67            if a.len() == b.len() {
68                a.cmp(b)
69            } else {
70                a.len().cmp(&b.len())
71            }
72        })
73        .opacity(0.6)
74        .size(10)
75        .colors(vec![Rgb(178, 34, 34), Rgb(65, 105, 225), Rgb(255, 140, 0)])
76        .shapes(vec![Shape::Circle, Shape::Square, Shape::Diamond])
77        .plot_title(Text::from("Penguin Morphology").font("Arial Bold").size(16))
78        .x_title(Text::from("body mass (g)").size(13))
79        .y_title(Text::from("flipper length (mm)").size(13).x(-0.11))
80        .legend_title(Text::from("Species").size(12))
81        .x_axis(&axis.clone().value_range(vec![2500.0, 6500.0]))
82        .y_axis(&axis.clone().value_range(vec![170.0, 240.0]))
83        .legend(&Legend::new().x(0.85).y(0.4))
84        .build();
85
86    let plot3 = BarPlot::builder()
87        .data(&animals_dataset)
88        .labels("animal")
89        .values("value")
90        .orientation(Orientation::Vertical)
91        .group("gender")
92        .sort_groups_by(|a, b| a.len().cmp(&b.len()))
93        .error("error")
94        .colors(vec![Rgb(255, 127, 80), Rgb(64, 224, 208)])
95        .plot_title(Text::from("Animal Statistics").font("Arial Bold").size(16))
96        .x_title(Text::from("animal").size(13))
97        .y_title(Text::from("value").size(13))
98        .legend_title(Text::from("Gender").size(12))
99        .legend(
100            &Legend::new()
101                .orientation(Orientation::Horizontal)
102                .x(0.35)
103                .y(0.9),
104        )
105        .build();
106
107    let plot4 = BoxPlot::builder()
108        .data(&penguins_dataset)
109        .labels("species")
110        .values("body_mass_g")
111        .orientation(Orientation::Vertical)
112        .group("gender")
113        .box_points(true)
114        .point_offset(-1.5)
115        .jitter(0.01)
116        .opacity(0.15)
117        .colors(vec![Rgb(0, 191, 255), Rgb(57, 255, 20), Rgb(255, 105, 180)])
118        .plot_title(
119            Text::from("Body Mass Distribution")
120                .font("Arial Bold")
121                .size(16),
122        )
123        .x_title(Text::from("species").size(13))
124        .y_title(Text::from("body mass (g)").size(13).x(-0.12))
125        .legend_title(Text::from("Gender").size(12))
126        .y_axis(&Axis::new().value_thousands(true))
127        .legend(&Legend::new().x(0.85).y(0.9))
128        .build();
129
130    let dimensions = Dimensions::new().width(1400).height(850).auto_size(false);
131
132    SubplotGrid::regular()
133        .plots(vec![&plot1, &plot2, &plot3, &plot4])
134        .rows(2)
135        .cols(2)
136        .v_gap(0.3)
137        .h_gap(0.2)
138        .dimensions(&dimensions)
139        .title(
140            Text::from("Scientific Data Visualization Dashboard")
141                .size(26)
142                .font("Arial Bold"),
143        )
144        .build()
145        .plot();
146}

Trait Implementations§

Source§

impl Clone for BoxPlot

Source§

fn clone(&self) -> BoxPlot

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Serialize for BoxPlot

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl PlotHelper for BoxPlot

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Key for T
where T: Clone,

Source§

fn align() -> usize

The alignment necessary for the key. Must return a power of two.
Source§

fn size(&self) -> usize

The size of the key in bytes.
Source§

unsafe fn init(&self, ptr: *mut u8)

Initialize the key in the given memory location. Read more
Source§

unsafe fn get<'a>(ptr: *const u8) -> &'a T

Get a reference to the key from the given memory location. Read more
Source§

unsafe fn drop_in_place(ptr: *mut u8)

Drop the key in place. Read more
Source§

impl<T> Plot for T
where T: PlotHelper + Serialize + Clone,

Source§

fn plot(&self)

Source§

fn write_html(&self, path: impl Into<String>)

Source§

fn to_json(&self) -> Result<String, Error>

Source§

fn to_html(&self) -> String

Source§

fn to_inline_html(&self, plot_div_id: Option<&str>) -> String

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Serialize for T
where T: Serialize + ?Sized,

Source§

fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<(), Error>

Source§

fn do_erased_serialize( &self, serializer: &mut dyn Serializer, ) -> Result<(), ErrorImpl>

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> PlanCallbackArgs for T

Source§

impl<T> PlanCallbackOut for T