1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/// Radius encoding mode for [`RosePlot`] sectors.
#[derive(Debug, Clone, Default)]
pub enum RoseEncoding {
/// Sector area is proportional to the value — perceptually accurate. **(default)**
#[default]
Area,
/// Sector radius is proportional to the value.
Radius,
}
/// Multi-series layout mode for [`RosePlot`].
#[derive(Debug, Clone, Default)]
pub enum RoseMode {
/// Series are stacked on top of each other within each sector. **(default)**
#[default]
Stacked,
/// Each series occupies its own sub-wedge within a sector.
Grouped,
}
/// A single data series for a [`RosePlot`].
#[derive(Debug, Clone)]
pub struct RoseSeries {
/// Series name (shown in legend).
pub name: String,
/// Per-sector values; indexed by sector position.
pub values: Vec<f64>,
/// Optional explicit CSS color. Falls back to palette.
pub color: Option<String>,
}
impl RoseSeries {
/// Create a new named series with given values.
pub fn new(name: impl Into<String>, values: Vec<f64>) -> Self {
RoseSeries {
name: name.into(),
values,
color: None,
}
}
}
/// Nightingale rose / coxcomb chart — a polar bar chart where each sector's
/// **area** (or radius) is proportional to the data value.
///
/// # Basic usage
///
/// ```rust,no_run
/// use kuva::plot::rose::RosePlot;
/// use kuva::render::{plots::Plot, layout::Layout, render::{render_multiple, render_rose}};
/// use kuva::backend::svg::SvgBackend;
///
/// let plot = RosePlot::new()
/// .with_slice("Jan", 30.0)
/// .with_slice("Feb", 20.0)
/// .with_slice("Mar", 45.0)
/// .with_slice("Apr", 38.0);
///
/// let plots = vec![Plot::Rose(plot)];
/// let layout = Layout::auto_from_plots(&plots).with_title("Monthly values");
/// let svg = SvgBackend.render_scene(&render_multiple(plots, layout));
/// std::fs::write("rose.svg", svg).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct RosePlot {
/// Data series. Single-series plots use `series[0]`.
pub series: Vec<RoseSeries>,
/// Sector labels (one per sector position).
pub labels: Vec<String>,
/// Radius encoding mode (default: [`RoseEncoding::Area`]).
pub encoding: RoseEncoding,
/// Multi-series layout mode (default: [`RoseMode::Stacked`]).
pub mode: RoseMode,
/// Start angle in degrees clockwise from north (default: 0.0).
pub start_angle: f64,
/// If `true` sectors proceed clockwise (default).
pub clockwise: bool,
/// Inner radius as a fraction of the outer radius (0–1); 0 = no hole. Default: 0.0.
pub inner_radius: f64,
/// Angular gap between adjacent sectors in degrees. Default: 1.0.
pub gap: f64,
/// Draw concentric grid rings. Default: `true`.
pub show_grid: bool,
/// Number of concentric grid rings. Default: 4.
pub grid_lines: usize,
/// Draw radial spoke lines. Default: `true`.
pub show_spokes: bool,
/// Draw sector labels around the perimeter. Default: `true`.
pub show_labels: bool,
/// Draw value labels at the tip of each sector. Default: `false`.
pub show_values: bool,
/// If set, a legend entry is rendered for each series.
pub legend_label: Option<String>,
}
impl Default for RosePlot {
fn default() -> Self {
Self::new()
}
}
impl RosePlot {
/// Create a [`RosePlot`] with default settings.
pub fn new() -> Self {
RosePlot {
series: vec![],
labels: vec![],
encoding: RoseEncoding::Area,
mode: RoseMode::Stacked,
start_angle: 0.0,
clockwise: true,
inner_radius: 0.0,
gap: 1.0,
show_grid: true,
grid_lines: 4,
show_spokes: true,
show_labels: true,
show_values: false,
legend_label: None,
}
}
// ── Data ─────────────────────────────────────────────────────────────────
/// Add a single sector (label + value) to the first (default) series.
/// Creates `series[0]` named "Values" if it doesn't exist yet.
pub fn with_slice(mut self, label: impl Into<String>, value: impl Into<f64>) -> Self {
self.labels.push(label.into());
if self.series.is_empty() {
self.series.push(RoseSeries::new("Values", vec![]));
}
self.series[0].values.push(value.into());
self
}
/// Add multiple slices from an iterator of `(label, value)`.
pub fn with_slices<S, V, I>(mut self, slices: I) -> Self
where
S: Into<String>,
V: Into<f64>,
I: IntoIterator<Item = (S, V)>,
{
for (label, value) in slices {
self = self.with_slice(label, value);
}
self
}
/// Set all sector labels at once.
pub fn with_x_labels<S, I>(mut self, labels: I) -> Self
where
S: Into<String>,
I: IntoIterator<Item = S>,
{
self.labels = labels.into_iter().map(Into::into).collect();
self
}
/// Add a stacked series. Sets mode to [`RoseMode::Stacked`].
pub fn with_stack<S, I>(mut self, name: impl Into<String>, values: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<f64>,
{
self.mode = RoseMode::Stacked;
self.series.push(RoseSeries::new(
name,
values.into_iter().map(Into::into).collect(),
));
self
}
/// Add a grouped series. Sets mode to [`RoseMode::Grouped`].
pub fn with_group<S, I>(mut self, name: impl Into<String>, values: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<f64>,
{
self.mode = RoseMode::Grouped;
self.series.push(RoseSeries::new(
name,
values.into_iter().map(Into::into).collect(),
));
self
}
/// Bin raw bearing values (0–360°) into `n_bins` equal sectors.
/// Sets degree labels if `labels` is currently empty; replaces (or creates)
/// `series[0]` named "Count".
pub fn with_bearing_data<I>(mut self, bearings: I, n_bins: usize) -> Self
where
I: IntoIterator<Item = f64>,
{
if n_bins == 0 {
return self;
}
let mut counts = vec![0_u64; n_bins];
let bin_size = 360.0 / n_bins as f64;
for b in bearings {
let b = ((b % 360.0) + 360.0) % 360.0;
let idx = (b / bin_size).floor() as usize;
let idx = idx.min(n_bins - 1);
counts[idx] += 1;
}
let values: Vec<f64> = counts.iter().map(|&c| c as f64).collect();
if self.labels.is_empty() {
self.labels = (0..n_bins)
.map(|i| format!("{:.0}°", i as f64 * bin_size))
.collect();
}
if self.series.is_empty() {
self.series.push(RoseSeries::new("Count", values));
} else {
self.series[0] = RoseSeries::new("Count", values);
}
self
}
/// Replace sector labels with compass directions derived from the current
/// number of sectors.
pub fn with_compass_labels(mut self) -> Self {
let n = self.n_sectors();
self.labels = compass_labels_for_n(n);
self
}
// ── Appearance ────────────────────────────────────────────────────────────
/// Set the radius encoding mode.
pub fn with_encoding(mut self, enc: RoseEncoding) -> Self {
self.encoding = enc;
self
}
/// Set the multi-series layout mode.
pub fn with_mode(mut self, mode: RoseMode) -> Self {
self.mode = mode;
self
}
/// Set the start angle in degrees clockwise from north.
pub fn with_start_angle(mut self, deg: f64) -> Self {
self.start_angle = deg;
self
}
/// Set the rotation direction.
pub fn with_clockwise(mut self, cw: bool) -> Self {
self.clockwise = cw;
self
}
/// Set the inner radius fraction (clamped to [0.0, 0.95]).
pub fn with_inner_radius(mut self, r: f64) -> Self {
self.inner_radius = r.clamp(0.0, 0.95);
self
}
/// Set the angular gap between adjacent sectors in degrees.
pub fn with_gap(mut self, gap: f64) -> Self {
self.gap = gap.max(0.0);
self
}
/// Show / hide concentric grid rings.
pub fn with_grid(mut self, show: bool) -> Self {
self.show_grid = show;
self
}
/// Set the number of concentric grid rings.
pub fn with_grid_lines(mut self, n: usize) -> Self {
self.grid_lines = n;
self
}
/// Show / hide radial spoke lines.
pub fn with_spokes(mut self, show: bool) -> Self {
self.show_spokes = show;
self
}
/// Show / hide sector labels around the perimeter.
pub fn with_show_labels(mut self, show: bool) -> Self {
self.show_labels = show;
self
}
/// Show / hide value labels at the tip of each sector.
pub fn with_show_values(mut self, show: bool) -> Self {
self.show_values = show;
self
}
/// Enable legend; pass a label string (used as the legend title or group name).
pub fn with_legend(mut self, label: impl Into<String>) -> Self {
self.legend_label = Some(label.into());
self
}
// ── Internal helpers ─────────────────────────────────────────────────────
/// Number of sectors (the maximum of labels length and max series values length).
pub(crate) fn n_sectors(&self) -> usize {
let label_n = self.labels.len();
let series_n = self
.series
.iter()
.map(|s| s.values.len())
.max()
.unwrap_or(0);
label_n.max(series_n)
}
/// Maximum data value used to scale the rings.
/// For Stacked: maximum cumulative sum per sector.
/// For Grouped: maximum individual value across all series and sectors.
pub(crate) fn max_total(&self) -> f64 {
if self.series.is_empty() {
return 0.0;
}
let n = self.n_sectors();
match self.mode {
RoseMode::Stacked => (0..n)
.map(|i| {
self.series
.iter()
.map(|s| s.values.get(i).copied().unwrap_or(0.0).max(0.0))
.sum::<f64>()
})
.fold(0.0_f64, f64::max),
RoseMode::Grouped => self
.series
.iter()
.flat_map(|s| s.values.iter().copied())
.fold(0.0_f64, f64::max),
}
}
}
/// Return compass direction labels for `n` evenly-spaced sectors.
///
/// If `n` divides evenly into the 16-point compass rose, the standard
/// cardinal / intercardinal abbreviations are used. Otherwise degree
/// strings like `"0°"`, `"15°"`, … are returned.
pub fn compass_labels_for_n(n: usize) -> Vec<String> {
if n == 0 {
return vec![];
}
let compass = [
"N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW",
"NW", "NNW",
];
if n <= 16 && 16 % n == 0 {
let stride = 16 / n;
(0..n).map(|i| compass[i * stride].to_string()).collect()
} else {
let step = 360.0 / n as f64;
(0..n).map(|i| format!("{:.0}°", i as f64 * step)).collect()
}
}