use super::axis::{Axis, ValueAxis};
use super::legend::Legend;
use super::series::{Series, SeriesAttr};
use crate::drawing::{Drawing, Shape};
#[derive(Debug, Clone, PartialEq)]
pub struct Chart {
pub chart_type: &'static str,
pub grouping: &'static str,
pub series: Vec<Series>,
pub legend: Legend,
pub show_legend: bool,
pub lang: String,
pub title: String,
pub print_margins: Vec<(String, String)>,
pub drawing: Drawing,
pub width: f64,
pub height: f64,
pub axes: Option<(Axis, Axis)>,
pub base_margin_top: f64,
pub base_margin_left: f64,
pub shapes: Vec<Shape>,
pub options: ChartOptions,
}
impl Default for Chart {
fn default() -> Self {
let mut drawing = Drawing::new();
drawing.left = 10;
drawing.top = 400;
drawing.set_height(400);
drawing.set_width(800);
Chart {
chart_type: "",
grouping: "standard",
series: Vec::new(),
legend: Legend::new(),
show_legend: true,
lang: "en-GB".to_string(),
title: String::new(),
print_margins: vec![
("b".to_string(), "0.75".to_string()),
("l".to_string(), "0.7".to_string()),
("r".to_string(), "0.7".to_string()),
("t".to_string(), "0.75".to_string()),
("header".to_string(), "0.3".to_string()),
("footer".to_string(), "0.3".to_string()),
],
drawing,
width: 0.6,
height: 0.6,
axes: None,
base_margin_top: 1.0,
base_margin_left: 0.0,
shapes: Vec::new(),
options: ChartOptions::default(),
}
}
}
impl Chart {
pub fn new() -> Self {
Chart::default()
}
pub fn add_series(&mut self, series: Series) -> &mut Self {
self.series.push(series);
self
}
pub fn add_shape(&mut self, shape: Shape) -> &mut Self {
self.shapes.push(shape);
self
}
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.title = title.into();
self
}
pub fn margin_top(&self) -> f64 {
self.base_margin_top.min(self.max_margin_top())
}
pub fn set_margin_top(&mut self, value: f64) {
self.base_margin_top = value;
}
pub fn max_margin_top(&self) -> f64 {
let mb = (Shape::FONT_HEIGHT + Shape::MARGIN_BOTTOM) as f64;
let plot_height = self.drawing.height() as f64 * self.height;
(self.drawing.height() as f64 - plot_height - mb) / self.drawing.height() as f64
}
pub fn margin_left(&self) -> f64 {
self.min_margin_left().max(self.base_margin_left)
}
pub fn set_margin_left(&mut self, value: f64) {
self.base_margin_left = value;
}
pub fn min_margin_left(&self) -> f64 {
let ml = (self.y_chars() * Shape::FONT_WIDTH) + Shape::MARGIN_LEFT;
ml as f64 / self.drawing.width() as f64
}
pub fn y_chars(&self) -> i64 {
let max = self
.series
.iter()
.filter_map(|s| s.max(SeriesAttr::Values))
.fold(0.0, f64::max);
format!("{}", max.trunc() as i64).len() as i64
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct GraphChart {
pub base: Chart,
pub x_axis: Axis,
pub y_axis: Axis,
pub auto_axis: bool,
}
impl GraphChart {
pub fn new(chart_type: &'static str) -> Self {
GraphChart {
base: Chart {
chart_type,
..Chart::default()
},
x_axis: Axis::category(),
y_axis: ValueAxis::new(),
auto_axis: true,
}
}
pub fn add_series(&mut self, series: Series) -> &mut Self {
self.base.add_series(series);
self
}
pub fn compute_axes(&mut self) {
let (min, max) = extremes(&self.base.series, SeriesAttr::Values);
self.y_axis.set_min(min);
self.y_axis.set_max(max);
self.y_axis.max_min();
if self.base.series.iter().all(|s| !s.x_reference.is_none()) {
let (min, max) = extremes(&self.base.series, SeriesAttr::XValues);
self.x_axis.set_min(min);
self.x_axis.set_max(max);
self.x_axis.max_min();
}
}
pub fn x_units(&self) -> usize {
self.base
.series
.iter()
.map(|s| s.values_for(SeriesAttr::Values).len())
.max()
.unwrap_or(0)
}
pub fn y_units(&self) -> f64 {
let drawing_height = crate::units::pixels_to_emu(self.base.drawing.height() as f64);
let plot_height = drawing_height as f64 * self.base.height;
let max = self.y_axis.max();
if max == 0.0 {
return plot_height;
}
plot_height / max
}
}
fn extremes(series: &[Series], attr: SeriesAttr) -> (f64, f64) {
let mut min = 0.0f64;
let mut max = 0.0f64;
for item in series {
if let Some(value) = item.max(attr) {
max = max.max(value);
}
if let Some(value) = item.min(attr) {
min = min.min(value);
}
}
(min, max)
}
#[derive(Debug, Clone, PartialEq)]
pub struct BarChart(pub GraphChart);
impl BarChart {
pub fn new() -> Self {
let mut chart = GraphChart::new("barChart");
chart.base.grouping = "clustered";
BarChart(chart)
}
pub fn add_series(&mut self, series: Series) -> &mut Self {
self.0.add_series(series);
self
}
pub fn compute_axes(&mut self) {
self.0.compute_axes();
}
pub fn into_chart(self) -> Chart {
let mut base = self.0.base;
base.axes = Some((self.0.x_axis, self.0.y_axis));
base
}
}
impl Default for BarChart {
fn default() -> Self {
BarChart::new()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct LineChart(pub GraphChart);
impl LineChart {
pub fn new() -> Self {
LineChart(GraphChart::new("lineChart"))
}
pub fn add_series(&mut self, series: Series) -> &mut Self {
self.0.add_series(series);
self
}
pub fn compute_axes(&mut self) {
self.0.compute_axes();
}
pub fn into_chart(self) -> Chart {
let mut base = self.0.base;
base.axes = Some((self.0.x_axis, self.0.y_axis));
base
}
}
impl Default for LineChart {
fn default() -> Self {
LineChart::new()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct PieChart(pub Chart);
impl PieChart {
pub fn new() -> Self {
PieChart(Chart {
chart_type: "pieChart",
..Chart::default()
})
}
pub fn add_series(&mut self, series: Series) -> &mut Self {
self.0.add_series(series);
self
}
pub fn into_chart(self) -> Chart {
self.0
}
}
impl Default for PieChart {
fn default() -> Self {
PieChart::new()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ScatterChart(pub GraphChart);
impl ScatterChart {
pub fn new() -> Self {
let mut chart = GraphChart::new("scatterChart");
chart.x_axis.axis_type = "valAx".to_string();
chart.x_axis.cross_between = "midCat".to_string();
chart.y_axis.cross_between = "midCat".to_string();
ScatterChart(chart)
}
pub fn into_chart(self) -> Chart {
let mut base = self.0.base;
base.axes = Some((self.0.x_axis, self.0.y_axis));
base
}
pub fn add_series(&mut self, series: Series) -> &mut Self {
self.0.add_series(series);
self
}
pub fn compute_axes(&mut self) {
self.0.compute_axes();
}
}
impl Default for ScatterChart {
fn default() -> Self {
ScatterChart::new()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct View3D {
pub rot_x: i64,
pub rot_y: i64,
pub depth_percent: i64,
pub right_angle_axes: bool,
}
impl View3D {
pub fn new() -> Self {
View3D {
rot_x: 15,
rot_y: 20,
depth_percent: 100,
right_angle_axes: false,
}
}
pub fn with_rot_x(mut self, degrees: i64) -> Self {
self.rot_x = degrees.clamp(-90, 90);
self
}
pub fn with_rot_y(mut self, degrees: i64) -> Self {
self.rot_y = degrees.clamp(-90, 90);
self
}
pub fn with_depth_percent(mut self, percent: i64) -> Self {
self.depth_percent = percent.clamp(1, 200);
self
}
pub fn with_right_angle_axes(mut self) -> Self {
self.right_angle_axes = true;
self
}
}
impl Default for View3D {
fn default() -> Self {
View3D::new()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ChartOptions {
pub radar_style: &'static str,
pub hole_size: Option<u16>,
pub first_slice_angle: Option<u16>,
pub bubble_3d: bool,
pub bubble_scale: Option<u16>,
pub show_negative_bubbles: bool,
pub size_represents: &'static str,
pub wireframe: bool,
pub of_pie_type: &'static str,
pub view_3d: Option<View3D>,
}
impl Default for ChartOptions {
fn default() -> Self {
ChartOptions {
radar_style: "standard",
hole_size: None,
first_slice_angle: None,
bubble_3d: false,
bubble_scale: None,
show_negative_bubbles: false,
size_represents: "area",
wireframe: false,
of_pie_type: "pie",
view_3d: None,
}
}
}
impl ChartOptions {
pub fn with_radar_style(mut self, style: &'static str) -> Self {
self.radar_style = style;
self
}
pub fn with_hole_size(mut self, percent: u16) -> Self {
self.hole_size = Some(percent.clamp(1, 90));
self
}
pub fn with_first_slice_angle(mut self, degrees: u16) -> Self {
self.first_slice_angle = Some(degrees.min(360));
self
}
pub fn three_d_bubbles(mut self) -> Self {
self.bubble_3d = true;
self
}
pub fn with_bubble_scale(mut self, percent: u16) -> Self {
self.bubble_scale = Some(percent.min(300));
self
}
pub fn with_negative_bubbles(mut self) -> Self {
self.show_negative_bubbles = true;
self
}
pub fn with_size_represents(mut self, kind: &'static str) -> Self {
self.size_represents = kind;
self
}
pub fn wireframe(mut self) -> Self {
self.wireframe = true;
self
}
pub fn with_of_pie_type(mut self, kind: &'static str) -> Self {
self.of_pie_type = kind;
self
}
pub fn with_view_3d(mut self, view: View3D) -> Self {
self.view_3d = Some(view);
self
}
}
macro_rules! graph_chart_type {
($(#[$meta:meta])* $name:ident, $tag:literal, $grouping:expr) => {
$(#[$meta])*
#[derive(Debug, Clone, PartialEq)]
pub struct $name(pub GraphChart);
impl $name {
pub fn new() -> Self {
let mut chart = GraphChart::new($tag);
chart.base.grouping = $grouping;
$name(chart)
}
pub fn with_options(options: ChartOptions) -> Self {
let mut chart = GraphChart::new($tag);
chart.base.grouping = $grouping;
chart.base.options = options;
$name(chart)
}
pub fn add_series(&mut self, series: Series) -> &mut Self {
self.0.add_series(series);
self
}
pub fn compute_axes(&mut self) {
self.0.compute_axes();
}
pub fn options(&self) -> &ChartOptions {
&self.0.base.options
}
pub fn set_options(&mut self, options: ChartOptions) -> &mut Self {
self.0.base.options = options;
self
}
pub fn into_chart(self) -> Chart {
let mut base = self.0.base;
base.axes = Some((self.0.x_axis, self.0.y_axis));
base
}
}
impl Default for $name {
fn default() -> Self {
$name::new()
}
}
};
}
macro_rules! axeless_chart_type {
($(#[$meta:meta])* $name:ident, $tag:literal) => {
$(#[$meta])*
#[derive(Debug, Clone, PartialEq)]
pub struct $name(pub Chart);
impl $name {
pub fn new() -> Self {
$name(Chart {
chart_type: $tag,
..Chart::default()
})
}
pub fn with_options(options: ChartOptions) -> Self {
let mut chart = Chart {
chart_type: $tag,
..Chart::default()
};
chart.options = options;
$name(chart)
}
pub fn add_series(&mut self, series: Series) -> &mut Self {
self.0.add_series(series);
self
}
pub fn options(&self) -> &ChartOptions {
&self.0.options
}
pub fn set_options(&mut self, options: ChartOptions) -> &mut Self {
self.0.options = options;
self
}
pub fn into_chart(self) -> Chart {
self.0
}
}
impl Default for $name {
fn default() -> Self {
$name::new()
}
}
};
}
graph_chart_type!(
AreaChart,
"areaChart",
"standard"
);
graph_chart_type!(
AreaChart3D,
"area3DChart",
"standard"
);
graph_chart_type!(
BarChart3D,
"bar3DChart",
"clustered"
);
graph_chart_type!(
LineChart3D,
"line3DChart",
"standard"
);
graph_chart_type!(
RadarChart,
"radarChart",
"standard"
);
graph_chart_type!(
BubbleChart,
"bubbleChart",
"standard"
);
graph_chart_type!(
StockChart,
"stockChart",
"standard"
);
graph_chart_type!(
SurfaceChart3D,
"surface3DChart",
"standard"
);
graph_chart_type!(
SurfaceChart,
"surfaceChart",
"standard"
);
axeless_chart_type!(
PieChart3D,
"pie3DChart"
);
axeless_chart_type!(
DoughnutChart,
"doughnutChart"
);
axeless_chart_type!(
ProjectedPieChart,
"ofPieChart"
);
impl BarChart {
pub fn with_options(options: ChartOptions) -> Self {
let mut chart = GraphChart::new("barChart");
chart.base.grouping = "clustered";
chart.base.options = options;
BarChart(chart)
}
}
impl LineChart {
pub fn with_options(options: ChartOptions) -> Self {
let mut chart = GraphChart::new("lineChart");
chart.base.options = options;
LineChart(chart)
}
}
impl ScatterChart {
pub fn with_options(options: ChartOptions) -> Self {
let mut chart = GraphChart::new("scatterChart");
chart.x_axis.axis_type = "valAx".to_string();
chart.x_axis.cross_between = "midCat".to_string();
chart.y_axis.cross_between = "midCat".to_string();
chart.base.options = options;
ScatterChart(chart)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::charts::reference::{CellValue, Reference, ReferenceDataType};
fn series_with(values: &[f64]) -> Series {
let cells: Vec<CellValue> = values.iter().map(|v| CellValue::Number(*v)).collect();
let mut reference = Reference::new("S", (0, 0), None, None, None).unwrap();
reference.set_values(cells, ReferenceDataType::Numeric);
Series::new(reference)
}
#[test]
fn chart_defaults_match_python() {
let chart = Chart::new();
assert!(chart.show_legend);
assert_eq!(chart.lang, "en-GB");
assert_eq!(chart.width, 0.6);
assert_eq!(chart.height, 0.6);
assert_eq!(chart.drawing.left, 10);
assert_eq!(chart.drawing.top, 400);
assert_eq!(chart.drawing.width(), 800);
assert_eq!(chart.drawing.height(), 400);
assert_eq!(chart.legend.position, "r");
assert_eq!(chart.print_margins.len(), 6);
}
#[test]
fn concrete_chart_types() {
assert_eq!(BarChart::new().0.base.chart_type, "barChart");
assert_eq!(BarChart::new().0.base.grouping, "clustered");
assert_eq!(LineChart::new().0.base.chart_type, "lineChart");
assert_eq!(PieChart::new().0.chart_type, "pieChart");
assert_eq!(ScatterChart::new().0.base.chart_type, "scatterChart");
assert_eq!(ScatterChart::new().0.x_axis.axis_type, "valAx");
}
#[test]
fn axes_scale_to_data() {
let mut chart = LineChart::new();
chart.add_series(series_with(&[1.0, 5.0, 9.0]));
chart.compute_axes();
assert!(chart.0.y_axis.max() >= 9.0);
assert!(chart.0.y_axis.min() <= 1.0);
assert!(chart.0.y_axis.unit() > 0.0);
}
#[test]
fn x_axis_skipped_without_x_values() {
let mut chart = LineChart::new();
chart.add_series(series_with(&[1.0, 2.0]));
let before = chart.0.x_axis.raw_max;
chart.compute_axes();
assert_eq!(chart.0.x_axis.raw_max, before);
assert_eq!(chart.0.x_units(), 2);
}
#[test]
fn y_chars_estimate_label_width() {
let mut chart = LineChart::new();
chart.add_series(series_with(&[1.0, 9999.0]));
assert_eq!(chart.0.base.y_chars(), 4);
}
#[test]
fn margins_are_clamped() {
let mut chart = LineChart::new();
chart.0.base.set_margin_top(0.1);
assert!(chart.0.base.margin_top() >= 0.1);
chart.0.base.set_margin_top(2.0);
assert!(chart.0.base.margin_top() <= 1.0);
assert!(chart.0.base.margin_left() >= 0.0);
}
#[test]
fn pie_chart_collects_series() {
let mut chart = PieChart::new();
chart.add_series(series_with(&[1.0]));
assert_eq!(chart.0.series.len(), 1);
}
#[test]
fn shapes_can_be_added() {
let mut chart = LineChart::new();
chart.0.base.add_shape(Shape::with_text("note"));
assert_eq!(chart.0.base.shapes.len(), 1);
assert_eq!(chart.0.base.shapes[0].text.as_deref(), Some("note"));
}
#[test]
fn value_axis_used_for_y() {
let chart = LineChart::new();
assert_eq!(chart.0.y_axis.axis_type, "valAx");
assert!(chart.0.y_axis.is_value_axis());
assert!(!chart.0.x_axis.is_value_axis());
}
}