mirror of
https://github.com/storytold/deckcraft.git
synced 2026-11-20 09:04:51 +00:00
Merge pull request #2071 from Hamza0101/fix/line-chart-value-labels
Charts: line series draw their value labels (#2066)
This commit is contained in:
3 files changed
+134
No files matched your search
@@ -1362,6 +1362,7 @@ impl Chart {
|
||||
.collect(),
|
||||
kind: Some(ChartType::Line),
|
||||
secondary_axis: true,
|
||||
data_labels: Some(false),
|
||||
..Default::default()
|
||||
});
|
||||
v.y2_min = Some(0.0);
|
||||
|
||||
@@ -494,6 +494,7 @@ fn draw_inner(ctx: &mut RenderContext, rctx: &Ctx, c: &Chart, frame: ChartFrame<
|
||||
to_axis: &to_axis,
|
||||
zero,
|
||||
base,
|
||||
text_color: text_col,
|
||||
error_marks: &mut err_marks,
|
||||
},
|
||||
);
|
||||
@@ -886,6 +887,7 @@ struct LineDrawing<'a, 'ctx> {
|
||||
to_axis: &'a dyn Fn(bool, f64) -> f64,
|
||||
zero: f64,
|
||||
base: f64,
|
||||
text_color: Rgba,
|
||||
error_marks: &'a mut Vec<(f64, f64, f64, f64, bool)>,
|
||||
}
|
||||
|
||||
@@ -914,10 +916,13 @@ fn draw_lines(ctx: &mut RenderContext, draw: &mut LineDrawing<'_, '_>) {
|
||||
let col = if area_kind { series_fill(rctx, c, si, Some(s)) } else { series_line(rctx, c, si, s) };
|
||||
let series_stats = s.error_bars.as_ref().map(|_| deckcraft_model::chart::SeriesStats::of(&s.values));
|
||||
let mut pts = vec![];
|
||||
// Each point's own value (not the stacked total), for its data label.
|
||||
let mut values = vec![];
|
||||
// Whether the series has any x value, found once rather than per point.
|
||||
let any_x = s.x_values.iter().flatten().next().is_some();
|
||||
for i in 0..ncat {
|
||||
let Some(v) = s.values.get(i).copied().flatten() else { continue };
|
||||
let own = v;
|
||||
let v = if stacked {
|
||||
let base_v = acc.get(i).copied().unwrap_or(0.0);
|
||||
if let Some(a) = acc.get_mut(i) {
|
||||
@@ -942,6 +947,7 @@ fn draw_lines(ctx: &mut RenderContext, draw: &mut LineDrawing<'_, '_>) {
|
||||
err_marks.push((x, to_axis(sec, lo), to_axis(sec, hi), base * 0.4, s.error_bars.as_ref().is_some_and(|e| e.end_cap)));
|
||||
}
|
||||
pts.push(Point::new(x, to_axis(sec, v)));
|
||||
values.push(own);
|
||||
}
|
||||
if pts.is_empty() {
|
||||
continue;
|
||||
@@ -969,6 +975,22 @@ fn draw_lines(ctx: &mut RenderContext, draw: &mut LineDrawing<'_, '_>) {
|
||||
ctx.fill_path(&kurbo::Circle::new(*q, 3.5).to_path(0.1));
|
||||
}
|
||||
}
|
||||
// A line series that asks for value labels (`c:dLbls/c:showVal`) shows each point's value
|
||||
// just above it, as bars do theirs (#2066). Area series keep none (theirs sit inside the
|
||||
// area), and scatter and bubble series, which also come here, are left as they were.
|
||||
if matches!(kind, ChartType::Line | ChartType::LineMarkers | ChartType::StackedLine) && c.series_data_labels(s) {
|
||||
let gap = base * 0.3 + 3.5;
|
||||
for (q, v) in pts.iter().zip(&values) {
|
||||
label(
|
||||
ctx,
|
||||
rctx,
|
||||
m,
|
||||
&c.data_label(s, *v),
|
||||
Rect::new(q.x - 40.0, q.y - gap - base * 1.4, q.x + 40.0, q.y - gap),
|
||||
LabelStyle { size: base * 0.9, align: Align::Center, anchor: Anchor::Bottom, col: draw.text_color, bold: false },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3238,6 +3238,117 @@ fn pie_data_labels_take_the_chart_text_colour_when_it_has_one() {
|
||||
assert!(count(&plain, &white) > count(&coloured, &white), "the labels were white before");
|
||||
}
|
||||
|
||||
/// #2066: a line series that asks for value labels (`c:dLbls/c:showVal`, chart-wide or its own)
|
||||
/// shows each point's value above it; with the chart's text red, the labels add red ink there.
|
||||
/// Area series still draw none (their labels belong inside the area, not on a point).
|
||||
#[test]
|
||||
fn line_chart_value_labels_are_drawn_above_their_points() {
|
||||
let draw = |kind: ChartType, labels: bool, own: bool| {
|
||||
let mut c = Chart::sample(kind);
|
||||
c.title = None;
|
||||
c.legend = None;
|
||||
c.text_color = Some(ColorRef::rgb(deckcraft_color::Rgba::rgb(255, 0, 0)));
|
||||
if own {
|
||||
c.series[0].data_labels = Some(labels);
|
||||
} else {
|
||||
c.data_labels = labels;
|
||||
}
|
||||
let sh = Shape { id: ShapeId(633), xfrm: Some(Xfrm::new(0.0, 0.0, 400.0, 300.0)), kind: ShapeKind::Chart(Box::new(c)), ..Default::default() };
|
||||
render_slide(&deck_with(vec![sh]), 0, &RenderOpts { scale: 1.0, ..Default::default() })
|
||||
};
|
||||
let red = |img: &Image| {
|
||||
(0..400u32)
|
||||
.flat_map(|x| (0..300u32).map(move |y| (x, y)))
|
||||
.filter(|(x, y)| {
|
||||
let p = img.pixel(*x, *y);
|
||||
p[0] > 200 && p[1] < 60 && p[2] < 60
|
||||
})
|
||||
.count()
|
||||
};
|
||||
for kind in [ChartType::Line, ChartType::LineMarkers] {
|
||||
let (off, on) = (red(&draw(kind, false, false)), red(&draw(kind, true, false)));
|
||||
assert!(on > off + 100, "{kind:?}: labels add red ink ({off} → {on})");
|
||||
let own = red(&draw(kind, true, true));
|
||||
assert!(own > off + 30, "{kind:?}: a series' own showVal shows its labels ({off} → {own})");
|
||||
}
|
||||
// Area series keep none, and scatter and bubble series (drawn by the same code) are unchanged.
|
||||
for kind in [ChartType::Area, ChartType::Scatter, ChartType::Bubble] {
|
||||
let (off, on) = (red(&draw(kind, false, false)), red(&draw(kind, true, false)));
|
||||
assert_eq!(on, off, "{kind:?}: no point labels");
|
||||
}
|
||||
}
|
||||
|
||||
/// The magenta pixels the labels add to a line chart of two series, only the second labelled,
|
||||
/// with the chart's text magenta (no series, gridline or axis line is): its axis labels are
|
||||
/// magenta too, so they are what the unlabelled chart has.
|
||||
fn line_label_ink(kind: ChartType, first: f64, second: f64) -> (Image, Vec<(u32, u32)>) {
|
||||
let off: std::collections::HashSet<_> = magenta_pixels(&line_label_render(kind, first, second, false)).into_iter().collect();
|
||||
let img = line_label_render(kind, first, second, true);
|
||||
let added = magenta_pixels(&img).into_iter().filter(|p| !off.contains(p)).collect();
|
||||
(img, added)
|
||||
}
|
||||
|
||||
fn line_label_render(kind: ChartType, first: f64, second: f64, labels: bool) -> Image {
|
||||
let mut c = Chart::sample(ChartType::Line);
|
||||
c.kind = kind;
|
||||
c.title = None;
|
||||
c.legend = None;
|
||||
c.series.truncate(2);
|
||||
c.series[0].values = vec![Some(first); 4];
|
||||
c.series[1].values = vec![Some(second); 4];
|
||||
c.series[1].data_labels = Some(labels);
|
||||
c.text_color = Some(ColorRef::rgb(deckcraft_color::Rgba::rgb(255, 0, 255)));
|
||||
let sh = Shape { id: ShapeId(634), xfrm: Some(Xfrm::new(0.0, 0.0, 400.0, 300.0)), kind: ShapeKind::Chart(Box::new(c)), ..Default::default() };
|
||||
render_slide(&deck_with(vec![sh]), 0, &RenderOpts { scale: 1.0, ..Default::default() })
|
||||
}
|
||||
|
||||
/// Magenta ink on white, its anti-aliased edges included.
|
||||
fn is_magenta(p: [u8; 4]) -> bool {
|
||||
p[0] > 200 && p[2] > 200 && p[1] < 200
|
||||
}
|
||||
|
||||
fn magenta_pixels(img: &Image) -> Vec<(u32, u32)> {
|
||||
(0..img.width).flat_map(|x| (0..img.height).map(move |y| (x, y))).filter(|(x, y)| is_magenta(img.pixel(*x, *y))).collect()
|
||||
}
|
||||
|
||||
/// #2066: in a stacked line chart a point's label is its own value, not the running total it is
|
||||
/// drawn at. The second series' 5s, stacked on 100s, are labels as wide as an unstacked series of
|
||||
/// 5s, and far narrower than one of 105s (the width: the pixel columns the label ink covers).
|
||||
#[test]
|
||||
fn a_stacked_line_labels_each_point_with_its_own_value() {
|
||||
let width = |kind, second| line_label_ink(kind, 100.0, second).1.iter().map(|(x, _)| *x).collect::<std::collections::HashSet<_>>().len();
|
||||
let (stacked, fives, totals) = (width(ChartType::StackedLine, 5.0), width(ChartType::Line, 5.0), width(ChartType::Line, 105.0));
|
||||
assert!(stacked > 0 && fives > 0, "labels are drawn ({stacked}, {fives})");
|
||||
assert!(stacked.abs_diff(fives) <= 4, "stacked 5s are labelled \"5\" ({stacked} columns vs {fives} for 5s)");
|
||||
assert!(stacked * 2 < totals, "not with the total \"105\" ({stacked} columns vs {totals} for 105s)");
|
||||
}
|
||||
|
||||
/// #2066: a line label sits just above its point: all its ink is above the series' line, and
|
||||
/// its lowest row is close to it.
|
||||
#[test]
|
||||
fn a_line_label_sits_just_above_its_point() {
|
||||
let (img, ink) = line_label_ink(ChartType::Line, 20.0, 50.0);
|
||||
assert!(!ink.is_empty(), "labels are drawn");
|
||||
let cols: std::collections::HashSet<u32> = ink.iter().map(|(x, _)| *x).collect();
|
||||
let (first, last) = (cols.iter().min().copied().unwrap(), cols.iter().max().copied().unwrap());
|
||||
// The labelled series' flat line at 50: the topmost coloured pixel in the plot's columns
|
||||
// between the labels (the other line is lower, at 20; the axis labels lie outside them).
|
||||
let line_top = (first..last)
|
||||
.filter(|x| !cols.iter().any(|c| c.abs_diff(*x) < 4))
|
||||
.filter_map(|x| {
|
||||
(0..img.height).find(|y| {
|
||||
let p = img.pixel(x, *y);
|
||||
let (hi, lo) = (p[0].max(p[1]).max(p[2]), p[0].min(p[1]).min(p[2]));
|
||||
hi - lo > 80 && !is_magenta(p)
|
||||
})
|
||||
})
|
||||
.min()
|
||||
.unwrap();
|
||||
let lowest = ink.iter().map(|(_, y)| *y).max().unwrap();
|
||||
assert!(lowest < line_top, "the labels are above the line (lowest ink row {lowest}, line at {line_top})");
|
||||
assert!(line_top - lowest < 20, "and just above it (lowest ink row {lowest}, line at {line_top})");
|
||||
}
|
||||
|
||||
/// #1165: an ellipse sized at the EMU limit, crossing the slide, made vello's flattener allocate a
|
||||
/// buffer from its on-screen length and abort. It is skipped; the rest of the slide still draws.
|
||||
#[test]
|
||||
|
||||
Reference in new issue
Block a user