HeatMap

Struct HeatMap 

Source
pub struct HeatMap {
    pub traces: Vec<Box<dyn Trace + 'static>>,
    pub layout: Layout,
    /* private fields */
}
Expand description

A structure representing a heat map.

The HeatMap struct enables the creation of heat map visualizations with options for color scaling, axis customization, legend adjustments, and data value formatting. Users can customize the color scale, adjust the color bar, and set titles for the plot and axes, as well as format ticks and scales for improved data readability.

§Arguments

  • data - A reference to the DataFrame containing the data to be plotted.
  • x - A string slice specifying the column name for x-axis values.
  • y - A string slice specifying the column name for y-axis values.
  • z - A string slice specifying the column name for z-axis values, which are represented by the color intensity.
  • facet - An optional string slice specifying the column name to be used for faceting (creating multiple subplots).
  • facet_config - An optional reference to a FacetConfig struct for customizing facet behavior (grid dimensions, scales, gaps, etc.).
  • auto_color_scale - An optional boolean for enabling automatic color scaling based on data.
  • color_bar - An optional reference to a ColorBar struct for customizing the color bar appearance.
  • color_scale - An optional Palette enum for specifying the color scale (e.g., Viridis).
  • reverse_scale - An optional boolean to reverse the color scale direction.
  • show_scale - An optional boolean to display the color scale on the plot.
  • plot_title - An optional Text struct for setting the title of the plot.
  • x_title - An optional Text struct for labeling the x-axis.
  • y_title - An optional Text struct for labeling the y-axis.
  • x_axis - An optional reference to an Axis struct for customizing x-axis appearance.
  • y_axis - An optional reference to an Axis struct for customizing y-axis appearance.

§Example

use plotlars::{ColorBar, HeatMap, Palette, Plot, Text, ValueExponent};
use polars::prelude::*;

let dataset = LazyCsvReader::new(PlPath::new("data/heatmap.csv"))
    .finish()
    .unwrap()
    .collect()
    .unwrap();

HeatMap::builder()
    .data(&dataset)
    .x("x")
    .y("y")
    .z("z")
    .color_bar(
        &ColorBar::new()
            .length(0.7)
            .value_exponent(ValueExponent::None)
            .separate_thousands(true)
            .tick_length(5)
            .tick_step(2500.0)
    )
    .plot_title(
        Text::from("Heat Map")
            .font("Arial")
            .size(18)
    )
    .color_scale(Palette::Viridis)
    .build()
    .plot();

Example

Fields§

§traces: Vec<Box<dyn Trace + 'static>>§layout: Layout

Implementations§

Source§

impl HeatMap

Source

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

Examples found in repository?
examples/heatmap.rs (line 11)
4fn main() {
5    let dataset = LazyCsvReader::new(PlPath::new("data/heatmap.csv"))
6        .finish()
7        .unwrap()
8        .collect()
9        .unwrap();
10
11    HeatMap::builder()
12        .data(&dataset)
13        .x("x")
14        .y("y")
15        .z("z")
16        .color_bar(
17            &ColorBar::new()
18                .length(0.7)
19                .value_exponent(ValueExponent::None)
20                .separate_thousands(true)
21                .tick_length(5)
22                .tick_step(2500.0),
23        )
24        .plot_title(Text::from("Heat Map").font("Arial").size(18))
25        .color_scale(Palette::Viridis)
26        .build()
27        .plot();
28}
More examples
Hide additional examples
examples/faceting.rs (line 229)
187fn heatmap_example() {
188    let mut regions = Vec::new();
189    let mut x_coords = Vec::new();
190    let mut y_coords = Vec::new();
191    let mut intensities = Vec::new();
192
193    let region_names = ["North", "South", "East", "West"];
194    let x_labels = ["X0", "X1", "X2", "X3", "X4"];
195    let y_labels = ["Y0", "Y1", "Y2", "Y3", "Y4"];
196
197    for (region_idx, region_name) in region_names.iter().enumerate() {
198        for (y_idx, y_label) in y_labels.iter().enumerate() {
199            for (x_idx, x_label) in x_labels.iter().enumerate() {
200                regions.push(*region_name);
201                x_coords.push(*x_label);
202                y_coords.push(*y_label);
203
204                let intensity = match region_idx {
205                    0 => (x_idx + y_idx * 5) as f64 * 4.0,
206                    1 => {
207                        let dx = x_idx as f64 - 2.0;
208                        let dy = y_idx as f64 - 2.0;
209                        100.0 - (dx * dx + dy * dy) * 4.0
210                    }
211                    2 => ((x_idx * x_idx + y_idx * y_idx) as f64).sqrt() * 10.0,
212                    3 => x_idx.max(y_idx) as f64 * 20.0,
213                    _ => 0.0,
214                };
215
216                intensities.push(intensity);
217            }
218        }
219    }
220
221    let heatmap_data = df! {
222        "region" => regions,
223        "x" => x_coords,
224        "y" => y_coords,
225        "intensity" => intensities,
226    }
227    .unwrap();
228
229    HeatMap::builder()
230        .data(&heatmap_data)
231        .x("x")
232        .y("y")
233        .z("intensity")
234        .facet("region")
235        .facet_config(&FacetConfig::new().rows(2).cols(2))
236        .plot_title(Text::from("Regional Heat Intensity Patterns").size(16))
237        .x_title(Text::from("X Coordinate"))
238        .y_title(Text::from("Y Coordinate"))
239        .build()
240        .plot();
241}
examples/subplot_grid.rs (line 210)
141fn irregular_grid_example() {
142    let dataset1 = LazyCsvReader::new(PlPath::new("data/penguins.csv"))
143        .finish()
144        .unwrap()
145        .select([
146            col("species"),
147            col("sex").alias("gender"),
148            col("flipper_length_mm").cast(DataType::Int16),
149            col("body_mass_g").cast(DataType::Int16),
150        ])
151        .collect()
152        .unwrap();
153
154    let axis = Axis::new()
155        .show_line(true)
156        .show_grid(true)
157        .value_thousands(true)
158        .tick_direction(TickDirection::OutSide);
159
160    let plot1 = Histogram::builder()
161        .data(&dataset1)
162        .x("body_mass_g")
163        .group("species")
164        .opacity(0.5)
165        .colors(vec![Rgb(255, 165, 0), Rgb(147, 112, 219), Rgb(46, 139, 87)])
166        .plot_title(Text::from("Histogram").x(0.0).y(1.35).size(14))
167        .x_title(Text::from("body mass (g)").x(0.94).y(-0.35))
168        .y_title(Text::from("count").x(-0.062).y(0.83))
169        .x_axis(&axis)
170        .y_axis(&axis)
171        .legend_title(Text::from("species"))
172        .legend(&Legend::new().x(0.87).y(1.2))
173        .build();
174
175    let dataset2 = LazyCsvReader::new(PlPath::new("data/stock_prices.csv"))
176        .finish()
177        .unwrap()
178        .collect()
179        .unwrap();
180
181    let increasing = Direction::new()
182        .line_color(Rgb(0, 200, 100))
183        .line_width(0.5);
184
185    let decreasing = Direction::new()
186        .line_color(Rgb(200, 50, 50))
187        .line_width(0.5);
188
189    let plot2 = CandlestickPlot::builder()
190        .data(&dataset2)
191        .dates("date")
192        .open("open")
193        .high("high")
194        .low("low")
195        .close("close")
196        .increasing(&increasing)
197        .decreasing(&decreasing)
198        .whisker_width(0.1)
199        .plot_title(Text::from("Candlestick").x(0.0).y(1.35).size(14))
200        .y_title(Text::from("price ($)").x(-0.06).y(0.76))
201        .y_axis(&Axis::new().show_axis(true).show_grid(true))
202        .build();
203
204    let dataset3 = LazyCsvReader::new(PlPath::new("data/heatmap.csv"))
205        .finish()
206        .unwrap()
207        .collect()
208        .unwrap();
209
210    let plot3 = HeatMap::builder()
211        .data(&dataset3)
212        .x("x")
213        .y("y")
214        .z("z")
215        .color_bar(
216            &ColorBar::new()
217                .value_exponent(ValueExponent::None)
218                .separate_thousands(true)
219                .tick_length(5)
220                .tick_step(5000.0),
221        )
222        .plot_title(Text::from("Heat Map").x(0.0).y(1.35).size(14))
223        .color_scale(Palette::Viridis)
224        .build();
225
226    SubplotGrid::irregular()
227        .plots(vec![
228            (&plot1, 0, 0, 1, 1),
229            (&plot2, 0, 1, 1, 1),
230            (&plot3, 1, 0, 1, 2),
231        ])
232        .rows(2)
233        .cols(2)
234        .v_gap(0.35)
235        .h_gap(0.05)
236        .title(
237            Text::from("Irregular Subplot Grid")
238                .size(16)
239                .font("Arial bold")
240                .y(0.95),
241        )
242        .build()
243        .plot();
244}

Trait Implementations§

Source§

impl Clone for HeatMap

Source§

fn clone(&self) -> HeatMap

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 HeatMap

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 HeatMap

Auto Trait Implementations§

§

impl Freeze for HeatMap

§

impl !RefUnwindSafe for HeatMap

§

impl !Send for HeatMap

§

impl !Sync for HeatMap

§

impl Unpin for HeatMap

§

impl !UnwindSafe for HeatMap

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> ErasedDestructor for T
where T: 'static,

Source§

impl<T> PlanCallbackArgs for T

Source§

impl<T> PlanCallbackOut for T