Skip to content

Commit bd0ac39

Browse files
committed
added example to show some colormaps
- this example was copy-pasted from the full_palette example and adapted
1 parent 13d2423 commit bd0ac39

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

plotters/examples/colormaps.rs

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
use plotters::prelude::*;
2+
3+
const OUT_FILE_NAME: &'static str = "plotters-doc-data/colormaps.png";
4+
5+
6+
fn main() -> Result<(), Box<dyn std::error::Error>> {
7+
let colormaps_rgb: [(Box<dyn ColorMap<RGBColor>>, &str); 4] = [
8+
(Box::new(ViridisRGB {}),"Viridis"),
9+
(Box::new(BlackWhite {}),"BlackWhite"),
10+
(Box::new(Bone {}),"Bone"),
11+
(Box::new(Copper {}),"Copper"),
12+
];
13+
14+
let colormaps_hsl: [(Box<dyn ColorMap<HSLColor>>, &str); 2] = [
15+
(Box::new(MandelbrotHSL {}), "MandelbrotHSL"),
16+
(Box::new(VulcanoHSL {}), "VulcanoHSL"),
17+
];
18+
19+
let size_x: i32 = 800;
20+
let n_colormaps = colormaps_rgb.len() + colormaps_hsl.len();
21+
let size_y = 200 + n_colormaps as u32 * 100;
22+
let root = BitMapBackend::new(OUT_FILE_NAME, (size_x as u32, size_y)).into_drawing_area();
23+
24+
root.fill(&WHITE)?;
25+
26+
let mut chart = ChartBuilder::on(&root)
27+
.caption("Demonstration of predefined colormaps", ("sans-serif", 20))
28+
.build_cartesian_2d(-150.0..size_x as f32+50.0, 0.0..3.0*(n_colormaps as f32))?;
29+
30+
use plotters::style::text_anchor::*;
31+
let centered = Pos::new(HPos::Center, VPos::Center);
32+
let label_style = TextStyle::from(("monospace", 14.0).into_font()).pos(centered);
33+
34+
let mut colormap_counter = 0;
35+
macro_rules! plot_colormaps(
36+
($colormap:expr) => {
37+
for (colormap, colormap_name) in $colormap.iter() {
38+
chart.draw_series(
39+
(0..size_x as i32).map(|x| {
40+
Rectangle::new([
41+
(x as f32, 3.0*(n_colormaps - 1 - colormap_counter) as f32 + 0.5),
42+
(x as f32+1.0, 3.0*(n_colormaps - 1 - colormap_counter) as f32 + 2.5)
43+
],
44+
colormap.get_color_normalized(x as f32, 0.0, size_x as f32).filled())
45+
})
46+
)?;
47+
chart.draw_series(
48+
[Text::new(colormap_name.to_owned(), (-75.0, 3.0*(n_colormaps-1-colormap_counter) as f32 + 1.5), &label_style)]
49+
)?;
50+
colormap_counter+=1;
51+
}
52+
}
53+
);
54+
55+
plot_colormaps!(colormaps_rgb);
56+
plot_colormaps!(colormaps_hsl);
57+
58+
59+
// To avoid the IO failure being ignored silently, we manually call the present function
60+
root.present().expect("Unable to write result to file, please make sure 'plotters-doc-data' dir exists under current dir");
61+
println!("Result has been saved to {}", OUT_FILE_NAME);
62+
63+
Ok(())
64+
}
65+
#[test]
66+
fn entry_point() {
67+
main().unwrap()
68+
}

0 commit comments

Comments
 (0)