use crate::data::{IntoSeries, Series};
use crate::mark::Categories;
use crate::render::Color;
#[derive(Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Bars<'a> {
pub(crate) placement: Placement,
pub(crate) values: Series<'a>,
pub(crate) color: Option<Color>,
pub(crate) label: Option<String>,
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "Option::is_none")
)]
pub(crate) color_by: Option<Categories>,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub(crate) enum Placement {
Bands(Vec<String>),
Spans { start: f64, width: f64 },
}
impl<'a> Bars<'a> {
pub fn new(
categories: impl IntoIterator<Item = impl Into<String>>,
values: impl IntoSeries<'a>,
) -> Bars<'a> {
let categories: Vec<String> = categories.into_iter().map(Into::into).collect();
let values = values.into_series();
let bars = Bars {
placement: Placement::Bands(categories),
values,
color: None,
label: None,
color_by: None,
};
bars.validate()
.expect("Bars::new requires one category per value");
bars
}
pub fn spans(start: f64, width: f64, values: impl IntoSeries<'a>) -> Bars<'a> {
let bars = Bars {
placement: Placement::Spans { start, width },
values: values.into_series(),
color: None,
label: None,
color_by: None,
};
bars.validate()
.expect("Bars::spans requires a finite start and a positive width");
bars
}
#[must_use]
pub fn color(mut self, color: Color) -> Bars<'a> {
self.color = Some(color);
self
}
#[must_use]
pub fn label(mut self, label: impl Into<String>) -> Bars<'a> {
self.label = Some(label.into());
self
}
#[must_use]
pub fn color_by(mut self, groups: impl IntoIterator<Item = impl Into<String>>) -> Bars<'a> {
self.color_by = Some(Categories::new(groups));
self.validate()
.expect("Bars::color_by requires one group per bar");
self
}
pub(crate) fn validate(&self) -> crate::Result<()> {
match &self.placement {
Placement::Bands(categories) => {
super::pair(
"Bars: categories and values",
categories.len(),
self.values.len(),
)?;
}
Placement::Spans { start, width }
if !(start.is_finite() && width.is_finite() && *width > 0.0) =>
{
return Err(crate::Error::InvalidParameter {
detail: "Bars spans need a finite start and finite positive width",
});
}
Placement::Spans { .. } => {}
}
if let Some(groups) = &self.color_by {
super::pair("Bars: color_by and values", groups.len(), self.values.len())?;
}
Ok(())
}
pub fn into_owned(self) -> Bars<'static> {
Bars {
placement: self.placement,
values: self.values.into_owned(),
color: self.color,
label: self.label,
color_by: self.color_by,
}
}
}
impl std::fmt::Debug for Bars<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Bars")
.field("bars", &self.values.len())
.field("color", &self.color)
.finish()
}
}
#[cfg(test)]
#[path = "tests/bars_tests.rs"]
mod tests;