Skip to main content

Heatmap

Struct Heatmap 

Source
pub struct Heatmap {
    pub data: Vec<Vec<f64>>,
    pub row_labels: Option<Vec<String>>,
    pub col_labels: Option<Vec<String>>,
    pub color_map: ColorMap,
    pub show_values: bool,
    pub legend_label: Option<String>,
    pub show_tooltips: bool,
    pub tooltip_labels: Option<Vec<String>>,
    pub x_range: Option<(f64, f64)>,
    pub y_range: Option<(f64, f64)>,
    pub cell_size: f64,
}
Expand description

Builder for a heatmap.

Renders a two-dimensional grid of colored cells. Cell color encodes the numeric value — each cell is mapped through a ColorMap after normalizing values to [0.0, 1.0] relative to the data range. A colorbar is always shown in the right margin.

§Axis labels

To display axis tick labels, pass them to Layout::with_x_categories (column labels) and Layout::with_y_categories (row labels).

§Row / column reordering (e.g. phylogenetic alignment)

Call with_labels first to associate each row and column with a name. Then call with_y_categories or with_x_categories with the desired order to reorder the data matrix in-place and update the stored labels.

use kuva::plot::{Heatmap, PhyloTree};
use kuva::render::layout::Layout;
use kuva::render::plots::Plot;

let labels: Vec<String> = ["A","B","C","D","E"].iter().map(|s| s.to_string()).collect();
let data = vec![
    vec![0.0, 1.0, 1.0, 1.0, 1.0],
    vec![1.0, 0.0, 0.4, 1.0, 1.0],
    vec![1.0, 0.4, 0.0, 1.0, 1.0],
    vec![1.0, 1.0, 1.0, 0.0, 1.0],
    vec![1.0, 1.0, 1.0, 1.0, 0.0],
];

let label_refs: Vec<&str> = labels.iter().map(|s| s.as_str()).collect();
let tree = PhyloTree::from_distance_matrix(&label_refs, &data);
let leaf_order = tree.leaf_labels_top_to_bottom();

let heatmap = Heatmap::new()
    .with_data(data)
    .with_labels(labels, vec![])    // record original row order
    .with_y_categories(leaf_order); // first leaf → top of heatmap

// row_labels is stored bottom-to-top — pass to Layout directly
let layout_cats = heatmap.row_labels.clone().unwrap();
let plots: Vec<Plot> = vec![Plot::PhyloTree(tree), Plot::Heatmap(heatmap)];
let layout = Layout::auto_from_plots(&plots)
    .with_y_categories(layout_cats); // axis tick labels in matching order

§Example

use kuva::plot::{Heatmap, ColorMap};
use kuva::backend::svg::SvgBackend;
use kuva::render::render::render_multiple;
use kuva::render::layout::Layout;
use kuva::render::plots::Plot;

let data = vec![
    vec![0.8, 0.3, 0.9],
    vec![0.4, 0.7, 0.1],
    vec![0.5, 0.9, 0.4],
];

let heatmap = Heatmap::new()
    .with_data(data)
    .with_color_map(ColorMap::Viridis);

let plots = vec![Plot::Heatmap(heatmap)];
let layout = Layout::auto_from_plots(&plots)
    .with_title("Heatmap")
    .with_x_categories(vec!["A".into(), "B".into(), "C".into()])
    .with_y_categories(vec!["X".into(), "Y".into(), "Z".into()]);

let svg = SvgBackend.render_scene(&render_multiple(plots, layout));
std::fs::write("heatmap.svg", svg).unwrap();

Fields§

§data: Vec<Vec<f64>>

Rows × columns grid of values. All rows must have the same length.

§row_labels: Option<Vec<String>>

Optional row labels — stored in the struct but rendered via Layout::with_y_categories.

§col_labels: Option<Vec<String>>

Optional column labels — stored in the struct but rendered via Layout::with_x_categories.

§color_map: ColorMap

Color map applied after normalizing values to [0.0, 1.0]. Defaults to ColorMap::Viridis.

§show_values: bool

When true, each cell displays its raw numeric value as text.

§legend_label: Option<String>§show_tooltips: bool§tooltip_labels: Option<Vec<String>>§x_range: Option<(f64, f64)>

Custom x-axis range (x_min, x_max). When set, cell columns are mapped linearly across this range instead of the default [0.5, cols+0.5].

§y_range: Option<(f64, f64)>

Custom y-axis range (y_min, y_max). When set, cell rows are mapped linearly across this range instead of the default [0.5, rows+0.5].

§cell_size: f64

Fraction of each cell’s natural size used when drawing the cell rect. 0.99 (default) leaves a 1% gap between cells, making cell boundaries visible. 1.0 draws cells flush — useful for large grids where the gap becomes a distracting grid pattern.

Implementations§

Source§

impl Heatmap

Source

pub fn new() -> Self

Create a heatmap with default settings.

Defaults: Viridis color map, no value overlay, no labels.

Source

pub fn with_data<U, T, I>(self, data: I) -> Self
where I: IntoIterator<Item = T>, T: IntoIterator<Item = U>, U: Into<f64>,

Set the grid data.

Accepts any iterable of iterables of numeric values. The outer iterator produces rows (top to bottom); the inner iterator produces columns (left to right). All rows must have the same number of columns.

let heatmap = Heatmap::new().with_data(vec![
    vec![1.0, 2.0, 3.0],
    vec![4.0, 5.0, 6.0],
]);
Source

pub fn with_labels(self, rows: Vec<String>, cols: Vec<String>) -> Self

Store row and column label strings in the struct.

These labels are used for tooltip text and as the reference mapping for with_y_categories / with_x_categories row/column reordering. To display them as axis tick labels, also pass them to Layout::with_y_categories and Layout::with_x_categories.

Source

pub fn with_y_categories( self, desired_order: impl IntoIterator<Item = impl Into<String>>, ) -> Self

Reorder heatmap rows so that desired_order[0] appears at the top of the rendered heatmap and desired_order[N-1] at the bottom.

desired_order is interpreted as top-to-bottom — matching the convention of PhyloTree::leaf_labels_top_to_bottom so that passing its result here aligns heatmap rows with tree leaves.

If row labels have already been set via with_labels, the data matrix rows are permuted accordingly. Any labels in desired_order not found in the current label set are silently skipped.

After calling this method, pass heatmap.row_labels.clone().unwrap() (which is stored in bottom-to-top order to match the y-axis convention) to Layout::with_y_categories to display the axis tick labels in the correct order.

let labels = ["A", "B", "C"];
let tree = PhyloTree::from_newick("((A:1,B:2):1,C:3);");
let leaf_order = tree.leaf_labels_top_to_bottom(); // top-to-bottom

let heatmap = Heatmap::new()
    .with_data(vec![vec![1.0,2.0,3.0], vec![4.0,5.0,6.0], vec![7.0,8.0,9.0]])
    .with_labels(labels.iter().map(|s| s.to_string()).collect(), vec![])
    .with_y_categories(leaf_order); // first label → top row

// row_labels is bottom-to-top — pass directly to Layout
let layout_cats = heatmap.row_labels.clone().unwrap();
let plots: Vec<Plot> = vec![Plot::Heatmap(heatmap)];
let layout = Layout::auto_from_plots(&plots).with_y_categories(layout_cats);
Source

pub fn with_x_categories( self, desired_order: impl IntoIterator<Item = impl Into<String>>, ) -> Self

Reorder heatmap columns to match desired_order and store the new column labels.

If column labels have already been set via with_labels, the data matrix columns are permuted so that each column’s label matches the corresponding position in desired_order. Any labels in desired_order that are not found in the current label set are silently skipped.

If no column labels have been set, the provided order is stored as-is (the caller is responsible for ensuring the data is already in this order).

After calling this method, pass the same order to Layout::with_x_categories to display the labels as axis tick marks.

Source

pub fn with_color_map(self, map: ColorMap) -> Self

Set the color map used to encode cell values (default ColorMap::Viridis).

let heatmap = Heatmap::new()
    .with_data(vec![vec![1.0, 2.0], vec![3.0, 4.0]])
    .with_color_map(ColorMap::Inferno);
Source

pub fn with_values(self) -> Self

Overlay numeric values inside each cell.

Values are formatted to two decimal places and centered in the cell. Most useful for small grids where the text remains legible.

Source

pub fn with_legend<S: Into<String>>(self, label: S) -> Self

Attach a legend label to this heatmap.

Source

pub fn with_tooltips(self) -> Self

Source

pub fn with_tooltip_labels( self, labels: impl IntoIterator<Item = impl Into<String>>, ) -> Self

Source

pub fn with_x_range(self, x_min: impl Into<f64>, x_max: impl Into<f64>) -> Self

Set the x-axis range (x_min, x_max) for the heatmap.

By default columns are mapped to [0.5, cols + 0.5] so that integer tick positions land on cell centres. Use this when the heatmap represents a scalar field over a physical domain (e.g. -10.0..10.0).

Source

pub fn with_y_range(self, y_min: impl Into<f64>, y_max: impl Into<f64>) -> Self

Set the y-axis range (y_min, y_max) for the heatmap.

By default rows are mapped to [0.5, rows + 0.5]. Use this when the heatmap represents a scalar field over a physical domain.

Source

pub fn with_cell_size(self, factor: impl Into<f64>) -> Self

Set the cell size as a fraction of each cell’s natural width and height.

The default 0.99 leaves a thin gap that makes cell boundaries visible. Pass 1.0 to draw cells flush with no gap — recommended for large grids where the gap becomes a distracting grid pattern.

Values are clamped to [0.5, 1.0].

Trait Implementations§

Source§

impl Clone for Heatmap

Source§

fn clone(&self) -> Heatmap

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Default for Heatmap

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl From<Heatmap> for Plot

Source§

fn from(p: Heatmap) -> Self

Converts to this type from the input type.

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> Finish for T

Source§

fn finish(self)

Does nothing but move self, equivalent to drop.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> 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<U, T> ToOwnedObj<U> for T
where U: FromObjRef<T>,

Source§

fn to_owned_obj(&self, data: FontData<'_>) -> U

Convert this type into T, using the provided data to resolve any offsets.
Source§

impl<U, T> ToOwnedTable<U> for T
where U: FromTableRef<T>,

Source§

fn to_owned_table(&self) -> U

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.