Skip to content

Commit 798444e

Browse files
committed
add pie unittests and fix docs
Signed-off-by: Andrei Gherghescu <[email protected]>
1 parent 006dfcf commit 798444e

File tree

4 files changed

+122
-19
lines changed

4 files changed

+122
-19
lines changed

docs/book/src/recipes/basic_charts/pie_charts.md

+6
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,12 @@ The `to_inline_html` method is used to produce the html plot displayed in this p
2020

2121
{{#include ../../../../../examples/basic_charts/out/basic_pie_chart.html}}
2222

23+
```rust,no_run
24+
{{#include ../../../../../examples/basic_charts/src/main.rs:basic_pie_chart_labels}}
25+
```
26+
27+
{{#include ../../../../../examples/basic_charts/out/basic_pie_chart_labels.html}}
28+
2329
## Grouped Pie Chart
2430
```rust,no_run
2531
{{#include ../../../../../examples/basic_charts/src/main.rs:grouped_donout_pie_charts}}

examples/basic_charts/src/main.rs

+20-2
Original file line numberDiff line numberDiff line change
@@ -825,7 +825,7 @@ fn table_chart(show: bool) -> Plot {
825825
// Pie Charts
826826
// ANCHOR: basic_pie_chart
827827
fn basic_pie_chart(show: bool) -> Plot {
828-
let values = vec![2, 3, 5];
828+
let values = vec![2, 3, 4];
829829
let labels = vec!["giraffes", "orangutans", "monkeys"];
830830
let t = Pie::new(values).labels(labels);
831831
let mut plot = Plot::new();
@@ -838,6 +838,23 @@ fn basic_pie_chart(show: bool) -> Plot {
838838
}
839839
// ANCHOR_END: basic_pie_chart
840840

841+
// ANCHOR: basic_pie_chart_labels
842+
fn basic_pie_chart_labels(show: bool) -> Plot {
843+
let labels = vec!["giraffes", "giraffes", "orangutans", "monkeys"]
844+
.iter()
845+
.map(|s| s.to_string())
846+
.collect();
847+
let t = Pie::<u32>::from_labels(labels);
848+
let mut plot = Plot::new();
849+
plot.add_trace(t);
850+
851+
if show {
852+
plot.show();
853+
}
854+
plot
855+
}
856+
// ANCHOR_END: basic_pie_chart_labels
857+
841858
// ANCHOR: pie_chart_text_control
842859
fn pie_chart_text_control(show: bool) -> Plot {
843860
let values = vec![2, 3, 4, 4];
@@ -992,7 +1009,8 @@ fn main() {
9921009
write_example_to_html(basic_sankey_diagram(false), "basic_sankey_diagram");
9931010

9941011
// Pie Charts
995-
write_example_to_html(basic_pie_chart(false), "basic_pie_chart");
1012+
write_example_to_html(basic_pie_chart(true), "basic_pie_chart");
1013+
write_example_to_html(basic_pie_chart_labels(true), "basic_pie_chart_labels");
9961014
write_example_to_html(pie_chart_text_control(false), "pie_chart_text_control");
9971015
write_example_to_html(
9981016
grouped_donout_pie_charts(false),

plotly/src/layout/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1071,8 +1071,8 @@ pub struct Annotation {
10711071
visible: Option<bool>,
10721072
/// Sets the text associated with this annotation. Plotly uses a subset of
10731073
/// HTML tags to do things like newline (<br>), bold (<b></b>), italics
1074-
/// (<i></i>), hyperlinks (<a href='...'></a>). Tags <em></em>, <sup></sup>, <sub></sub>
1075-
/// <span></span> are also supported.
1074+
/// (<i></i>), hyperlinks (<a href='...'></a>). Tags <em></em>, <sup></sup>,
1075+
/// <sub></sub> <span></span> are also supported.
10761076
text: Option<String>,
10771077
/// Sets the angle at which the `text` is drawn with respect to the
10781078
/// horizontal.

plotly/src/traces/pie.rs

+94-15
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,28 @@ pub enum PieDirection {
3535
///
3636
/// assert_eq!(serde_json::to_value(trace).unwrap(), expected);
3737
/// ```
38+
/// # Using only labels
39+
///
40+
/// Build a new Pie Chart by only assigning the labels field. The Pie chart
41+
/// will be generated by counting the number of unique labels, see [Pie::labels]
42+
/// field description. Note that to create a Pie chart by using this
43+
/// function, the type parameter `P` needs to be specialized, this can be
44+
/// done by doing
45+
///
46+
/// ```
47+
/// use plotly::Pie;
48+
///
49+
/// let labels = vec!["giraffes", "giraffes", "orangutans", "monkeys"].iter().map(|s| s.to_string()).collect();
50+
///
51+
/// let trace = Pie::<u32>::from_labels(labels);
52+
///
53+
/// let expected = serde_json::json!({
54+
/// "type": "pie",
55+
/// "labels": ["giraffes", "giraffes", "orangutans", "monkeys"],
56+
/// });
57+
///
58+
/// assert_eq!(serde_json::to_value(trace).unwrap(), expected);
59+
/// ```
3860
#[serde_with::skip_serializing_none]
3961
#[derive(Serialize, Clone, Debug, FieldSetter)]
4062
#[field_setter(box_self, kind = "trace")]
@@ -86,9 +108,9 @@ where
86108
/// Additionally, every attributes that can be specified per-point (the
87109
/// ones that are arrayOk: true) are available. Finally, the template
88110
/// string has access to variables label, color, value, percent and text.
89-
/// Anything contained in tag \<extra\> is displayed in the secondary box, for
90-
/// example “<extra>{fullData.name}</extra>”. To hide the secondary box
91-
/// completely, use an empty tag <extra></extra>.
111+
/// Anything contained in tag \<extra\> is displayed in the secondary box,
112+
/// for example “<extra>{fullData.name}</extra>”. To hide the secondary
113+
/// box completely, use an empty tag <extra></extra>.
92114
#[serde(rename = "hovertemplate")]
93115
hover_template: Option<Dim<String>>,
94116
/// Sets hover text elements associated with each sector. If a single
@@ -144,9 +166,9 @@ where
144166
/// axis and colorbar title.text, annotation text rangeselector,
145167
/// updatemenues and sliders label text all support meta. To access the
146168
/// trace meta values in an attribute in the same trace, simply use
147-
/// %{meta\[i\]} where i is the index or key of the meta item in question. To
148-
/// access trace meta in layout attributes, use %{data[n[.meta\[i\]} where i
149-
/// is the index or key of the meta and n is the trace index.
169+
/// %{meta\[i\]} where i is the index or key of the meta item in question.
170+
/// To access trace meta in layout attributes, use %{data[n[.meta\[i\]}
171+
/// where i is the index or key of the meta and n is the trace index.
150172
meta: Option<NumOrString>,
151173
/// Sets the trace name. The trace name appears as the legend item and on
152174
/// hover.
@@ -186,10 +208,10 @@ where
186208
/// Template string used for rendering the information text that appear on
187209
/// points. Note that this will override textinfo. Variables are
188210
/// inserted using %{variable}, for example “y: %{y}”. Numbers are formatted
189-
/// using d3-format’s syntax %{variable:d3-format}, for example “Price: %{y:$.2f}”.
190-
/// <https://github.com/d3/d3-format/tree/v1.4.5#d3-format> for details on the formatting syntax.
191-
/// Dates are formatted using d3-time-format’s syntax %{variable|d3-time-format}, for example
192-
/// “Day: %{2019-01-01|%A}”. <https://github.com/d3/d3-time-format/tree/v2.2.3#locale_format> for details on the date formatting syntax.
211+
/// using d3-format’s syntax %{variable:d3-format}, for example “Price:
212+
/// %{y:$.2f}”. <https://github.com/d3/d3-format/tree/v1.4.5#d3-format> for details on the formatting syntax.
213+
/// Dates are formatted using d3-time-format’s syntax
214+
/// %{variable|d3-time-format}, for example “Day: %{2019-01-01|%A}”. <https://github.com/d3/d3-time-format/tree/v2.2.3#locale_format> for details on the date formatting syntax.
193215
/// Every attributes that can be specified per-point (the ones that are
194216
/// arrayOk: true) are available. Finally, the template string has
195217
/// access to variables label, color, value, percent and text.
@@ -282,9 +304,36 @@ impl<P> Pie<P>
282304
where
283305
P: Serialize + Clone + 'static,
284306
{
285-
pub fn new(x: Vec<P>) -> Box<Self> {
307+
/// Build a new Pie Chart by only assigning the values field
308+
pub fn new(values: Vec<P>) -> Box<Self> {
309+
Box::new(Self {
310+
values: Some(values),
311+
..Default::default()
312+
})
313+
}
314+
315+
/// Same as [Pie::new()]
316+
pub fn from_values(values: Vec<P>) -> Box<Self> {
286317
Box::new(Self {
287-
values: Some(x),
318+
values: Some(values),
319+
..Default::default()
320+
})
321+
}
322+
323+
/// Build a new Pie Chart by only assigning the labels field. The Pie chart
324+
/// will be generated by counting the number of unique labels, see
325+
/// [Pie::labels] field description. Note that to create a Pie chart by
326+
/// using this function, the type parameter `P` needs to be specialized,
327+
/// this can be done by doing
328+
/// ```
329+
/// use plotly::Pie;
330+
///
331+
/// let labels = vec!["giraffes", "giraffes", "orangutans", "monkeys"].iter().map(|s| s.to_string()).collect();
332+
/// let trace = Pie::<u32>::from_labels(labels);
333+
/// ```
334+
pub fn from_labels(labels: Vec<String>) -> Box<Self> {
335+
Box::new(Self {
336+
labels: Some(labels),
288337
..Default::default()
289338
})
290339
}
@@ -306,8 +355,8 @@ mod tests {
306355
use super::*;
307356

308357
#[test]
309-
fn test_serialize_scatter_mapbox() {
310-
let scatter_mapbox = Pie::new(vec![45, 55])
358+
fn serialize_pie() {
359+
let pie_trace = Pie::new(vec![45, 55])
311360
.name("pie")
312361
.automargin(true)
313362
.direction(PieDirection::Clockwise)
@@ -374,6 +423,36 @@ mod tests {
374423
"uirevision": 6,
375424
});
376425

377-
assert_eq!(to_value(scatter_mapbox).unwrap(), expected);
426+
assert_eq!(to_value(pie_trace).unwrap(), expected);
427+
}
428+
429+
#[test]
430+
fn new_from_values() {
431+
let values = vec![2.2, 3.3, 4.4];
432+
let trace = Pie::from_values(values);
433+
434+
let expected = serde_json::json!({
435+
"type": "pie",
436+
"values": [2.2, 3.3, 4.4],
437+
});
438+
439+
assert_eq!(to_value(trace).unwrap(), expected);
440+
}
441+
442+
#[test]
443+
fn new_from_labels() {
444+
let labels = vec!["giraffes", "giraffes", "orangutans", "monkeys"]
445+
.iter()
446+
.map(|s| s.to_string())
447+
.collect();
448+
449+
let trace = Pie::<u32>::from_labels(labels);
450+
451+
let expected = serde_json::json!({
452+
"type": "pie",
453+
"labels": ["giraffes", "giraffes", "orangutans", "monkeys"],
454+
});
455+
456+
assert_eq!(to_value(trace).unwrap(), expected);
378457
}
379458
}

0 commit comments

Comments
 (0)