emilk / emilk/egui_plot

Stacked bars are offset by a wrong value

Open
#23 0 comments 0 reactions 0 assignees View on GitHub
bug
Dominant language
Rust
Stars
468
Forks
108
Avg merge
15m
Merged PRs (30d)
3

Description

**Describe the bug**
I was working on a little app with a stacked bar chart, and came across this possible bug (black lines were added in Paint for illustrative purposes):
![filtered](https://github.com/emilk/egui/assets/11886186/ff205baa-1fe4-45ef-8032-941475ae8ea2)

Each bar chart is based upon a `Vec<(f64, f64)>`, which contains pairs of `(value, frequency)`, all vectors have the same length, `value` isn't being used as the `Bar`'s argument intentionally.
```Rust
// declared elsewhere
frequencies: Vec>,

// plot rendering
let mut charts = vec![];
for (frequencies, label) in self.frequencies.iter().zip(self.labels.iter()) {
let bars = frequencies
.iter()
.enumerate()
.filter(|(_, (_, f))| f > &0.0)
.map(|(i, (v, f))| Bar::new(i as f64, *f).width(self.width).name(v))
.collect();

let mut chart = BarChart::new(bars).name(&label);
if !self.vertical {
chart = chart.horizontal();
}

if charts.len() > 0 {
let other_charts: Vec<_> = charts.iter().collect();
chart = chart.stack_on(&other_charts);
}

charts.push(chart);
}
```
Zero frequencies are filtered out, so the total number of bars will vary. The reason for filtering is that a `Bar` with zero height will be rendered anyway, and to me it looks a little confusing (the plot's aspect ratio is different, but all values are the same):
![non-filtered](https://github.com/emilk/egui/assets/11886186/e9163512-e2ea-45f6-ac50-b4304c2f05ec)
Here, the offset values are correct, since the number of bars in both charts is the same.

**To Reproduce**
The easiest way to reproduce this behavior is to modify the demo app by commenting out [this line](https://github.com/emilk/egui/blob/ded8dbd45bc8616475c364878f6b8e2f7293d12c/crates/egui_demo_lib/src/demo/plot_demo.rs#L976):
![demo-app](https://github.com/emilk/egui/assets/11886186/71e60648-a4ef-4e18-9a78-e5ccc9c6479a)

**Expected behavior**
I expect the modified demo app to look like this:
![demo-app-fix](https://github.com/emilk/egui/assets/11886186/c29911c9-7524-4e98-8b21-eb9d9ccfdf91)

**Additional context**
I assume it's a bug, since I never used stacked bar charts before.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.