feat(barchar): add BarChart::grouped constructor (#1513)

Add a new constructor to the `BarChart` widget that allows creating a
grouped barchart with multiple groups of bars.

Also add a new constructor to the `BarGroup` widget that allows creating
a group of bars with a label.
This commit is contained in:
Josh McKinney
2025-05-14 05:00:50 -07:00
committed by GitHub
parent dcb0e5dffc
commit e15fefa922
2 changed files with 45 additions and 0 deletions

View File

@@ -172,6 +172,31 @@ impl<'a> BarChart<'a> {
}
}
/// Creates a new `BarChart` widget with a group of bars.
///
/// # Examples
///
/// ```rust
/// use ratatui::widgets::{Bar, BarChart, BarGroup};
///
/// BarChart::grouped(vec![
/// BarGroup::with_label(
/// "Group 1",
/// vec![Bar::with_label("A", 10), Bar::with_label("B", 20)],
/// ),
/// BarGroup::with_label(
/// "Group 2",
/// [Bar::with_label("C", 30), Bar::with_label("D", 40)],
/// ),
/// ]);
/// ```
pub fn grouped<T: Into<Vec<BarGroup<'a>>>>(groups: T) -> Self {
Self {
data: groups.into(),
..Default::default()
}
}
/// Add group of bars to the `BarChart`
///
/// # Examples

View File

@@ -43,6 +43,26 @@ impl<'a> BarGroup<'a> {
}
}
/// Creates a new `BarGroup` with the given bars and label.
///
/// # Examples
///
/// ```
/// use ratatui::style::{Style, Stylize};
/// use ratatui::widgets::{Bar, BarGroup};
///
/// let group = BarGroup::with_label(
/// "Group1",
/// vec![Bar::with_label("A", 10), Bar::with_label("B", 20)],
/// );
/// ```
pub fn with_label<T: Into<Line<'a>>, B: Into<Vec<Bar<'a>>>>(label: T, bars: B) -> Self {
Self {
label: Some(label.into()),
bars: bars.into(),
}
}
/// Set the group label
///
/// `label` can be a [`&str`], [`String`] or anything that can be converted into [`Line`].