aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/chart/context/cartesian2d/draw_impl.rs5
-rw-r--r--src/chart/dual_coord.rs2
-rw-r--r--src/chart/series.rs4
-rw-r--r--src/coord/ranged1d/types/datetime.rs128
-rw-r--r--src/drawing/area.rs16
-rw-r--r--src/element/pie.rs14
-rw-r--r--src/evcxr.rs2
-rw-r--r--src/lib.rs168
-rw-r--r--src/series/line_series.rs3
-rw-r--r--src/style/colors/colormaps.rs311
-rw-r--r--src/style/colors/mod.rs8
-rw-r--r--src/style/font/ab_glyph.rs160
-rw-r--r--src/style/font/mod.rs26
-rw-r--r--src/style/font/ttf.rs4
-rw-r--r--src/style/mod.rs3
15 files changed, 748 insertions, 106 deletions
diff --git a/src/chart/context/cartesian2d/draw_impl.rs b/src/chart/context/cartesian2d/draw_impl.rs
index 6dafa08..1745273 100644
--- a/src/chart/context/cartesian2d/draw_impl.rs
+++ b/src/chart/context/cartesian2d/draw_impl.rs
@@ -119,10 +119,7 @@ impl<'a, DB: DrawingBackend, X: Ranged, Y: Ranged> ChartContext<'a, DB, Cartesia
y1 = axis_range.end;
}
- area.draw(&PathElement::new(
- vec![(x0, y0), (x1, y1)],
- *axis_style,
- ))?;
+ area.draw(&PathElement::new(vec![(x0, y0), (x1, y1)], *axis_style))?;
}
Ok(axis_range)
diff --git a/src/chart/dual_coord.rs b/src/chart/dual_coord.rs
index d5960e0..434e347 100644
--- a/src/chart/dual_coord.rs
+++ b/src/chart/dual_coord.rs
@@ -20,7 +20,7 @@ use plotters_backend::{BackendCoord, DrawingBackend};
/// This situation is quite common, for example, we with two different coodinate system.
/// For instance this example <img src="https://plotters-rs.github.io/plotters-doc-data/twoscale.png"></img>
/// This is done by attaching a second coordinate system to ChartContext by method [ChartContext::set_secondary_coord](struct.ChartContext.html#method.set_secondary_coord).
-/// For instance of dual coordinate charts, see [this example](https://github.com/38/plotters/blob/master/examples/two-scales.rs#L15).
+/// For instance of dual coordinate charts, see [this example](https://github.com/plotters-rs/plotters/blob/master/examples/two-scales.rs#L15).
/// Note: `DualCoordChartContext` is always deref to the chart context.
/// - If you want to configure the secondary axis, method [DualCoordChartContext::configure_secondary_axes](struct.DualCoordChartContext.html#method.configure_secondary_axes)
/// - If you want to draw a series using secondary coordinate system, use [DualCoordChartContext::draw_secondary_series](struct.DualCoordChartContext.html#method.draw_secondary_series). And method [ChartContext::draw_series](struct.ChartContext.html#method.draw_series) will always use primary coordinate spec.
diff --git a/src/chart/series.rs b/src/chart/series.rs
index 8c430cb..4aecf6a 100644
--- a/src/chart/series.rs
+++ b/src/chart/series.rs
@@ -250,9 +250,7 @@ impl<'a, 'b, DB: DrawingBackend + 'a, CT: CoordTranslate> SeriesLabelStyle<'a, '
continue;
}
- funcs.push(
- draw_func.unwrap_or(&|p: BackendCoord| EmptyElement::at(p).into_dyn()),
- );
+ funcs.push(draw_func.unwrap_or(&|p: BackendCoord| EmptyElement::at(p).into_dyn()));
label_element.push_line(label_text);
}
diff --git a/src/coord/ranged1d/types/datetime.rs b/src/coord/ranged1d/types/datetime.rs
index 9b12358..0a532f8 100644
--- a/src/coord/ranged1d/types/datetime.rs
+++ b/src/coord/ranged1d/types/datetime.rs
@@ -4,12 +4,12 @@ use std::ops::{Add, Range, Sub};
use crate::coord::ranged1d::{
AsRangedCoord, DefaultFormatting, DiscreteRanged, KeyPointHint, NoDefaultFormatting, Ranged,
- ValueFormatter,
+ ReversibleRanged, ValueFormatter,
};
/// The trait that describe some time value. This is the uniformed abstraction that works
/// for both Date, DateTime and Duration, etc.
-pub trait TimeValue: Eq {
+pub trait TimeValue: Eq + Sized {
type DateType: Datelike + PartialOrd;
/// Returns the date that is no later than the time
@@ -20,6 +20,8 @@ pub trait TimeValue: Eq {
fn earliest_after_date(date: Self::DateType) -> Self;
/// Returns the duration between two time value
fn subtract(&self, other: &Self) -> Duration;
+ /// Add duration to time value
+ fn add(&self, duration: &Duration) -> Self;
/// Instantiate a date type for current time value;
fn ymd(&self, year: i32, month: u32, date: u32) -> Self::DateType;
/// Cast current date type into this type
@@ -46,6 +48,31 @@ pub trait TimeValue: Eq {
(f64::from(limit.1 - limit.0) * value_days / total_days) as i32 + limit.0
}
+
+ /// Map pixel to coord spec
+ fn unmap_coord(point: i32, begin: &Self, end: &Self, limit: (i32, i32)) -> Self {
+ let total_span = end.subtract(begin);
+ let offset = (point - limit.0) as i64;
+
+ // Check if nanoseconds fit in i64
+ if let Some(total_ns) = total_span.num_nanoseconds() {
+ let pixel_span = (limit.1 - limit.0) as i64;
+ let factor = total_ns / pixel_span;
+ let remainder = total_ns % pixel_span;
+ if factor == 0
+ || i64::MAX / factor > offset.abs()
+ || (remainder == 0 && i64::MAX / factor >= offset.abs())
+ {
+ let nano_seconds = offset * factor + (remainder * offset) / pixel_span;
+ return begin.add(&Duration::nanoseconds(nano_seconds));
+ }
+ }
+
+ // Otherwise, use days
+ let total_days = total_span.num_days() as f64;
+ let days = (((offset as f64) * total_days) / ((limit.1 - limit.0) as f64)) as i64;
+ begin.add(&Duration::days(days))
+ }
}
impl TimeValue for NaiveDate {
@@ -62,6 +89,9 @@ impl TimeValue for NaiveDate {
fn subtract(&self, other: &NaiveDate) -> Duration {
*self - *other
}
+ fn add(&self, other: &Duration) -> NaiveDate {
+ *self + *other
+ }
fn ymd(&self, year: i32, month: u32, date: u32) -> Self::DateType {
NaiveDate::from_ymd(year, month, date)
@@ -86,6 +116,9 @@ impl<Z: TimeZone> TimeValue for Date<Z> {
fn subtract(&self, other: &Date<Z>) -> Duration {
self.clone() - other.clone()
}
+ fn add(&self, other: &Duration) -> Date<Z> {
+ self.clone() + *other
+ }
fn ymd(&self, year: i32, month: u32, date: u32) -> Self::DateType {
self.timezone().ymd(year, month, date)
@@ -115,6 +148,9 @@ impl<Z: TimeZone> TimeValue for DateTime<Z> {
fn subtract(&self, other: &DateTime<Z>) -> Duration {
self.clone() - other.clone()
}
+ fn add(&self, other: &Duration) -> DateTime<Z> {
+ self.clone() + *other
+ }
fn ymd(&self, year: i32, month: u32, date: u32) -> Self::DateType {
self.timezone().ymd(year, month, date)
@@ -144,6 +180,9 @@ impl TimeValue for NaiveDateTime {
fn subtract(&self, other: &NaiveDateTime) -> Duration {
*self - *other
}
+ fn add(&self, other: &Duration) -> NaiveDateTime {
+ *self + *other
+ }
fn ymd(&self, year: i32, month: u32, date: u32) -> Self::DateType {
NaiveDate::from_ymd(year, month, date)
@@ -663,6 +702,19 @@ where
}
}
+impl<DT> ReversibleRanged for RangedDateTime<DT>
+where
+ DT: Datelike + Timelike + TimeValue + Clone + PartialOrd,
+ DT: Add<Duration, Output = DT>,
+ DT: Sub<DT, Output = Duration>,
+ RangedDate<DT::DateType>: Ranged<ValueType = DT::DateType>,
+{
+ /// Perform the reverse mapping
+ fn unmap(&self, input: i32, limit: (i32, i32)) -> Option<Self::ValueType> {
+ Some(TimeValue::unmap_coord(input, &self.0, &self.1, limit))
+ }
+}
+
/// The coordinate that for duration of time
#[derive(Clone)]
pub struct RangedDuration(Duration, Duration);
@@ -1168,4 +1220,76 @@ mod test {
assert_eq!(coord1.index_of(&coord1.from_index(i).unwrap()).unwrap(), i);
}
}
+
+ #[test]
+ fn test_datetime_with_unmap() {
+ let start_time = Utc.ymd(2021, 1, 1).and_hms(8, 0, 0);
+ let end_time = Utc.ymd(2023, 1, 1).and_hms(8, 0, 0);
+ let mid = Utc.ymd(2022, 1, 1).and_hms(8, 0, 0);
+ let coord: RangedDateTime<_> = (start_time..end_time).into();
+ let pos = coord.map(&mid, (1000, 2000));
+ assert_eq!(pos, 1500);
+ let value = coord.unmap(pos, (1000, 2000));
+ assert_eq!(value, Some(mid));
+ }
+
+ #[test]
+ fn test_naivedatetime_with_unmap() {
+ let start_time = NaiveDate::from_ymd(2021, 1, 1).and_hms_milli(8, 0, 0, 0);
+ let end_time = NaiveDate::from_ymd(2023, 1, 1).and_hms_milli(8, 0, 0, 0);
+ let mid = NaiveDate::from_ymd(2022, 1, 1).and_hms_milli(8, 0, 0, 0);
+ let coord: RangedDateTime<_> = (start_time..end_time).into();
+ let pos = coord.map(&mid, (1000, 2000));
+ assert_eq!(pos, 1500);
+ let value = coord.unmap(pos, (1000, 2000));
+ assert_eq!(value, Some(mid));
+ }
+
+ #[test]
+ fn test_date_with_unmap() {
+ let start_date = Utc.ymd(2021, 1, 1);
+ let end_date = Utc.ymd(2023, 1, 1);
+ let mid = Utc.ymd(2022, 1, 1);
+ let coord: RangedDate<Date<_>> = (start_date..end_date).into();
+ let pos = coord.map(&mid, (1000, 2000));
+ assert_eq!(pos, 1500);
+ let value = coord.unmap(pos, (1000, 2000));
+ assert_eq!(value, Some(mid));
+ }
+
+ #[test]
+ fn test_naivedate_with_unmap() {
+ let start_date = NaiveDate::from_ymd(2021, 1, 1);
+ let end_date = NaiveDate::from_ymd(2023, 1, 1);
+ let mid = NaiveDate::from_ymd(2022, 1, 1);
+ let coord: RangedDate<NaiveDate> = (start_date..end_date).into();
+ let pos = coord.map(&mid, (1000, 2000));
+ assert_eq!(pos, 1500);
+ let value = coord.unmap(pos, (1000, 2000));
+ assert_eq!(value, Some(mid));
+ }
+
+ #[test]
+ fn test_datetime_unmap_for_nanoseconds() {
+ let start_time = Utc.ymd(2021, 1, 1).and_hms(8, 0, 0);
+ let end_time = start_time + Duration::nanoseconds(1900);
+ let mid = start_time + Duration::nanoseconds(950);
+ let coord: RangedDateTime<_> = (start_time..end_time).into();
+ let pos = coord.map(&mid, (1000, 2000));
+ assert_eq!(pos, 1500);
+ let value = coord.unmap(pos, (1000, 2000));
+ assert_eq!(value, Some(mid));
+ }
+
+ #[test]
+ fn test_datetime_unmap_for_nanoseconds_small_period() {
+ let start_time = Utc.ymd(2021, 1, 1).and_hms(8, 0, 0);
+ let end_time = start_time + Duration::nanoseconds(400);
+ let coord: RangedDateTime<_> = (start_time..end_time).into();
+ let value = coord.unmap(2000, (1000, 2000));
+ assert_eq!(value, Some(end_time));
+ let mid = start_time + Duration::nanoseconds(200);
+ let value = coord.unmap(500, (0, 1000));
+ assert_eq!(value, Some(mid));
+ }
}
diff --git a/src/drawing/area.rs b/src/drawing/area.rs
index 2e5c3fe..9519f37 100644
--- a/src/drawing/area.rs
+++ b/src/drawing/area.rs
@@ -87,7 +87,7 @@ impl Rect {
.map(|(a, b)| (*a, *b))
.collect();
- // Justify: this is actually needed. Because we need to return a iterator that have
+ // Justify: this is actually needed. Because we need to return a iterator that have
// static life time, thus we need to copy the value to a buffer and then turn the buffer
// into a iterator.
#[allow(clippy::needless_collect)]
@@ -97,14 +97,12 @@ impl Rect {
.map(|(a, b)| (*a, *b))
.collect();
- ysegs
- .into_iter()
- .flat_map(move |(y0, y1)| {
- xsegs
- .clone()
- .into_iter()
- .map(move |(x0, x1)| Self { x0, y0, x1, y1 })
- })
+ ysegs.into_iter().flat_map(move |(y0, y1)| {
+ xsegs
+ .clone()
+ .into_iter()
+ .map(move |(x0, x1)| Self { x0, y0, x1, y1 })
+ })
}
/// Make the coordinate in the range of the rectangle
diff --git a/src/element/pie.rs b/src/element/pie.rs
index 9529834..79fa927 100644
--- a/src/element/pie.rs
+++ b/src/element/pie.rs
@@ -109,18 +109,14 @@ impl<'a, DB: DrawingBackend, Label: Display> Drawable<DB> for Pie<'a, (i32, i32)
let radian_increment = PI / 180.0 / self.radius.sqrt() * 2.0;
let mut perc_labels = Vec::new();
for (index, slice) in self.sizes.iter().enumerate() {
- let slice_style =
- self.colors
- .get(index)
- .ok_or_else(|| DrawingErrorKind::FontError(Box::new(
- PieError::LengthMismatch,
- )))?;
+ let slice_style = self
+ .colors
+ .get(index)
+ .ok_or_else(|| DrawingErrorKind::FontError(Box::new(PieError::LengthMismatch)))?;
let label = self
.labels
.get(index)
- .ok_or_else(|| DrawingErrorKind::FontError(Box::new(
- PieError::LengthMismatch,
- )))?;
+ .ok_or_else(|| DrawingErrorKind::FontError(Box::new(PieError::LengthMismatch)))?;
// start building wedge line against the previous edge
let mut points = vec![*self.center];
let ratio = slice / self.total;
diff --git a/src/evcxr.rs b/src/evcxr.rs
index 8117d35..3438d34 100644
--- a/src/evcxr.rs
+++ b/src/evcxr.rs
@@ -53,7 +53,7 @@ pub fn evcxr_bitmap_figure<
size: (u32, u32),
draw: Draw,
) -> SVGWrapper {
- const PIXEL_SIZE : usize = 3;
+ const PIXEL_SIZE: usize = 3;
let mut buf = Vec::new();
buf.resize((size.0 as usize) * (size.1 as usize) * PIXEL_SIZE, 0);
let root = BitMapBackend::with_buffer(&mut buf, size).into_drawing_area();
diff --git a/src/lib.rs b/src/lib.rs
index 873288b..86a75d0 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,7 +1,7 @@
#![warn(missing_docs)]
/*!
-# Plotters - A Rust drawing library focus on data plotting for both WASM and native applications 🦀📈🚀
+# Plotters - A Rust drawing library focusing on data plotting for both WASM and native applications 🦀📈🚀
<a href="https://crates.io/crates/plotters">
<img style="display: inline!important" src="https://img.shields.io/crates/v/plotters.svg"></img>
@@ -16,14 +16,14 @@
<img style="display: inline! important" src="https://img.shields.io/badge/docs-development-lightgrey.svg"></img>
</a>
-Plotters is drawing library designed for rendering figures, plots, and charts, in pure rust. Plotters supports various types of back-ends,
+Plotters is a drawing library designed for rendering figures, plots, and charts, in pure Rust. Plotters supports various types of back-ends,
including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
-- A new Plotters Developer's Guide is working in progress. The preview version is available at [here](https://plotters-rs.github.io/book).
-- To try Plotters with interactive Jupyter notebook, or view [here](https://plotters-rs.github.io/plotters-doc-data/evcxr-jupyter-integration.html) for the static HTML version.
+- A new Plotters Developer's Guide is a work in progress. The preview version is available [here](https://plotters-rs.github.io/book).
+- Try Plotters with an interactive Jupyter notebook, or view [here](https://plotters-rs.github.io/plotters-doc-data/evcxr-jupyter-integration.html) for the static HTML version.
- To view the WASM example, go to this [link](https://plotters-rs.github.io/wasm-demo/www/index.html)
-- Currently we have all the internal code ready for console plotting, but a console based backend is still not ready. See [this example](https://github.com/38/plotters/blob/master/examples/console.rs) for how to plotting on Console with a customized backend.
-- Plotters now moved all backend code to sperate repositories, check [FAQ list](#faq-list) for details
+- Currently we have all the internal code ready for console plotting, but a console based backend is still not ready. See [this example](https://github.com/plotters-rs/plotters/blob/master/plotters/examples/console.rs) for how to plot on console with a customized backend.
+- Plotters has moved all backend code to separate repositories, check [FAQ list](#faq-list) for details
- Some interesting [demo projects](#demo-projects) are available, feel free to try them out.
## Gallery
@@ -34,7 +34,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
</a>
<div class="galleryText">
Multiple Plot
- <a href="https://github.com/38/plotters/blob/master/plotters/examples/chart.rs">[code]</a>
+ <a href="https://github.com/plotters-rs/plotters/blob/master/plotters/examples/chart.rs">[code]</a>
</div>
</div>
@@ -44,7 +44,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
</a>
<div class="galleryText">
Candlestick Plot
- <a href="https://github.com/38/plotters/blob/master/plotters/examples/stock.rs">[code]</a>
+ <a href="https://github.com/plotters-rs/plotters/blob/master/plotters/examples/stock.rs">[code]</a>
</div>
</div>
@@ -54,7 +54,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
</a>
<div class="galleryText">
Histogram
- <a href="https://github.com/38/plotters/blob/master/plotters/examples/histogram.rs">[code]</a>
+ <a href="https://github.com/plotters-rs/plotters/blob/master/plotters/examples/histogram.rs">[code]</a>
</div>
</div>
@@ -82,7 +82,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
</a>
<div class="galleryText">
Mandelbrot set
- <a href="https://github.com/38/plotters/blob/master/plotters/examples/mandelbrot.rs">[code]</a>
+ <a href="https://github.com/plotters-rs/plotters/blob/master/plotters/examples/mandelbrot.rs">[code]</a>
</div>
</div>
@@ -112,7 +112,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
</a>
<div class="galleryText">
Histogram with Scatter
- <a href="https://github.com/38/plotters/blob/master/plotters/examples/normal-dist.rs">[code]</a>
+ <a href="https://github.com/plotters-rs/plotters/blob/master/plotters/examples/normal-dist.rs">[code]</a>
</div>
</div>
@@ -122,7 +122,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
</a>
<div class="galleryText">
Dual Y-Axis Example
- <a href="https://github.com/38/plotters/blob/master/plotters/examples/two-scales.rs">[code]</a>
+ <a href="https://github.com/plotters-rs/plotters/blob/master/plotters/examples/two-scales.rs">[code]</a>
</div>
</div>
@@ -132,7 +132,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
</a>
<div class="galleryText">
The Matplotlib Matshow Example
- <a href="https://github.com/38/plotters/blob/master/plotters/examples/matshow.rs">[code]</a>
+ <a href="https://github.com/plotters-rs/plotters/blob/master/plotters/examples/matshow.rs">[code]</a>
</div>
</div>
@@ -142,7 +142,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
</a>
<div class="galleryText">
The Sierpinski Carpet
- <a href="https://github.com/38/plotters/blob/master/plotters/examples/sierpinski.rs">[code]</a>
+ <a href="https://github.com/plotters-rs/plotters/blob/master/plotters/examples/sierpinski.rs">[code]</a>
</div>
</div>
@@ -152,7 +152,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
</a>
<div class="galleryText">
The 1D Gaussian Distribution
- <a href="https://github.com/38/plotters/blob/master/plotters/examples/nomal-dist2.rs">[code]</a>
+ <a href="https://github.com/plotters-rs/plotters/blob/master/plotters/examples/nomal-dist2.rs">[code]</a>
</div>
</div>
@@ -162,7 +162,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
</a>
<div class="galleryText">
The 1D Gaussian Distribution
- <a href="https://github.com/38/plotters/blob/master/plotters/examples/errorbar.rs">[code]</a>
+ <a href="https://github.com/plotters-rs/plotters/blob/master/plotters/examples/errorbar.rs">[code]</a>
</div>
</div>
@@ -172,7 +172,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
</a>
<div class="galleryText">
Monthly Time Coordinate
- <a href="https://github.com/38/plotters/blob/master/plotters/examples/slc-temp.rs">[code]</a>
+ <a href="https://github.com/plotters-rs/plotters/blob/master/plotters/examples/slc-temp.rs">[code]</a>
</div>
</div>
@@ -182,7 +182,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
</a>
<div class="galleryText">
Monthly Time Coordinate
- <a href="https://github.com/38/plotters/blob/master/plotters/examples/area-chart.rs">[code]</a>
+ <a href="https://github.com/plotters-rs/plotters/blob/master/plotters/examples/area-chart.rs">[code]</a>
</div>
</div>
@@ -192,7 +192,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
</a>
<div class="galleryText">
Koch Snowflake
- <a href="https://github.com/38/plotters/blob/master/plotters/examples/snowflake.rs">[code]</a>
+ <a href="https://github.com/plotters-rs/plotters/blob/master/plotters/examples/snowflake.rs">[code]</a>
</div>
</div>
@@ -203,7 +203,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
</a>
<div class="galleryText">
Koch Snowflake Animation
- <a href="https://github.com/38/plotters/blob/master/plotters/examples/animation.rs">[code]</a>
+ <a href="https://github.com/plotters-rs/plotters/blob/master/plotters/examples/animation.rs">[code]</a>
</div>
</div>
@@ -214,7 +214,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
</a>
<div class="galleryText">
Drawing on a Console
- <a href="https://github.com/38/plotters/blob/master/plotters/examples/console.rs">[code]</a>
+ <a href="https://github.com/plotters-rs/plotters/blob/master/plotters/examples/console.rs">[code]</a>
</div>
</div>
@@ -224,7 +224,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
</a>
<div class="galleryText">
Drawing bitmap on chart
- <a href="https://github.com/38/plotters/blob/master/plotters/examples/blit-bitmap.rs">[code]</a>
+ <a href="https://github.com/plotters-rs/plotters/blob/master/plotters/examples/blit-bitmap.rs">[code]</a>
</div>
</div>
@@ -234,7 +234,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
</a>
<div class="galleryText">
The boxplot demo
- <a href="https://github.com/38/plotters/blob/master/plotters/examples/boxplot.rs">[code]</a>
+ <a href="https://github.com/plotters-rs/plotters/blob/master/plotters/examples/boxplot.rs">[code]</a>
</div>
</div>
@@ -244,7 +244,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
</a>
<div class="galleryText">
3D plot rendering
- <a href="https://github.com/38/plotters/blob/master/plotters/examples/3d-plot.rs">[code]</a>
+ <a href="https://github.com/plotters-rs/plotters/blob/master/plotters/examples/3d-plot.rs">[code]</a>
</div>
</div>
@@ -254,7 +254,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
</a>
<div class="galleryText">
2-Var Gussian Distribution PDF
- <a href="https://github.com/38/plotters/blob/master/plotters/examples/3d-plot2.rs">[code]</a>
+ <a href="https://github.com/plotters-rs/plotters/blob/master/plotters/examples/3d-plot2.rs">[code]</a>
</div>
</div>
@@ -264,7 +264,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
</a>
<div class="galleryText">
COVID-19 Visualization
- <a href="https://github.com/38/plotters/blob/master/plotters/examples/tick_control.rs">[code]</a>
+ <a href="https://github.com/plotters-rs/plotters/blob/master/plotters/examples/tick_control.rs">[code]</a>
</div>
</div>
@@ -280,8 +280,8 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
* [Plotting in Rust](#plotting-in-rust)
* [Plotting on HTML5 canvas with WASM Backend](#plotting-on-html5-canvas-with-wasm-backend)
* [What types of figure are supported?](#what-types-of-figure-are-supported)
- * [Concepts by examples](#concepts-by-examples)
- + [Drawing Back-ends](#drawing-back-ends)
+ * [Concepts by example](#concepts-by-example)
+ + [Drawing Backends](#drawing-backends)
+ [Drawing Area](#drawing-area)
+ [Elements](#elements)
+ [Composable Elements](#composable-elements)
@@ -303,7 +303,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
To use Plotters, you can simply add Plotters into your `Cargo.toml`
```toml
[dependencies]
-plotters = "0.3.1"
+plotters = "0.3.3"
```
And the following code draws a quadratic function. `src/main.rs`,
@@ -346,27 +346,27 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
## Demo Projects
-To learn how to use Plotters in different scenarios by checking out the following demo projects:
+To learn how to use Plotters in different scenarios, check out the following demo projects:
- WebAssembly + Plotters: [plotters-wasm-demo](https://github.com/plotters-rs/plotters-wasm-demo)
- minifb + Plotters: [plotters-minifb-demo](https://github.com/plotters-rs/plotters-minifb-demo)
-- GTK + Plotters: [plotters-gtk-demo](https://github.com/plotters/plotters-gtk-demo)
+- GTK + Plotters: [plotters-gtk-demo](https://github.com/plotters-rs/plotters-gtk-demo)
## Trying with Jupyter evcxr Kernel Interactively
-Plotters now supports integrate with `evcxr` and is able to interactively drawing plots in Jupyter Notebook.
+Plotters now supports integration with `evcxr` and is able to interactively draw plots in Jupyter Notebook.
The feature `evcxr` should be enabled when including Plotters to Jupyter Notebook.
The following code shows a minimal example of this.
```text
-:dep plotters = { git = "https://github.com/38/plotters", default_features = false, features = ["evcxr"] }
+:dep plotters = { version = "^0.3.5", default_features = false, features = ["evcxr", "all_series", "all_elements"] }
extern crate plotters;
use plotters::prelude::*;
let figure = evcxr_figure((640, 480), |root| {
- root.fill(&WHITE);
+ root.fill(&WHITE)?;
let mut chart = ChartBuilder::on(&root)
.caption("y=x^2", ("Arial", 50).into_font())
.margin(5)
@@ -396,7 +396,7 @@ figure
## Interactive Tutorial with Jupyter Notebook
-*This tutorial is now working in progress and isn't complete*
+*This tutorial is a work in progress and isn't complete*
Thanks to the evcxr, now we have an interactive tutorial for Plotters!
To use the interactive notebook, you must have Jupyter and evcxr installed on your computer.
@@ -406,57 +406,55 @@ After that, you should be able to start your Jupyter server locally and load the
```bash
git clone https://github.com/38/plotters-doc-data
-cd plotteres-doc-data
+cd plotters-doc-data
jupyter notebook
```
And select the notebook called `evcxr-jupyter-integration.ipynb`.
-Also, there's a static HTML version of this notebook available at the [this location](https://plotters-rs.github.io/plotters-doc-data/evcxr-jupyter-integration.html)
+Also, there's a static HTML version of this notebook available at [this location](https://plotters-rs.github.io/plotters-doc-data/evcxr-jupyter-integration.html)
## Plotting in Rust
-Rust is a perfect language for data visualization. Although there are many mature visualization libraries in many different languages.
-But Rust is one of the best languages fits the need.
+Rust is a perfect language for data visualization. Although there are many mature visualization libraries in many different languages, Rust is one of the best languages that fits the need.
* **Easy to use** Rust has a very good iterator system built into the standard library. With the help of iterators,
-Plotting in Rust can be as easy as most of the high-level programming languages. The Rust based plotting library
+plotting in Rust can be as easy as most of the high-level programming languages. The Rust based plotting library
can be very easy to use.
-* **Fast** If you need rendering a figure with trillions of data points,
-Rust is a good choice. Rust's performance allows you to combine data processing step
+* **Fast** If you need to render a figure with trillions of data points,
+Rust is a good choice. Rust's performance allows you to combine the data processing step
and rendering step into a single application. When plotting in high-level programming languages,
e.g. Javascript or Python, data points must be down-sampled before feeding into the plotting
program because of the performance considerations. Rust is fast enough to do the data processing and visualization
within a single program. You can also integrate the
-figure rendering code into your application handling a huge amount of data and visualize it in real-time.
+figure rendering code into your application to handle a huge amount of data and visualize it in real-time.
-* **WebAssembly Support** Rust is one of few the language with the best WASM support. Plotting in Rust could be
+* **WebAssembly Support** Rust is one of the languages with the best WASM support. Plotting in Rust could be
very useful for visualization on a web page and would have a huge performance improvement comparing to Javascript.
## Plotting on HTML5 canvas with WASM Backend
-Plotters currently supports backend that uses the HTML5 canvas. To use the WASM support, you can simply use
+Plotters currently supports a backend that uses the HTML5 canvas. To use WASM, you can simply use
`CanvasBackend` instead of other backend and all other API remains the same!
There's a small demo for Plotters + WASM available at [here](https://github.com/plotters-rs/plotters-wasm-demo).
To play with the deployed version, follow this [link](https://plotters-rs.github.io/wasm-demo/www/index.html).
-
## What types of figure are supported?
Plotters is not limited to any specific type of figure.
You can create your own types of figures easily with the Plotters API.
-But Plotters provides some builtin figure types for convenience.
+Plotters does provide some built-in figure types for convenience.
Currently, we support line series, point series, candlestick series, and histogram.
And the library is designed to be able to render multiple figure into a single image.
But Plotter is aimed to be a platform that is fully extendable to support any other types of figure.
-## Concepts by examples
+## Concepts by example
-### Drawing Back-ends
-Plotters can use different drawing back-ends, including SVG, BitMap, and even real-time rendering. For example, a bitmap drawing backend.
+### Drawing Backends
+Plotters can use different drawing backends, including SVG, BitMap, and even real-time rendering. For example, a bitmap drawing backend.
```rust
use plotters::prelude::*;
@@ -475,10 +473,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
### Drawing Area
Plotters uses a concept called drawing area for layout purpose.
-Plotters support multiple integrating into a single image.
+Plotters supports integrating multiple figures into a single image.
This is done by creating sub-drawing-areas.
-Besides that, the drawing area also allows the customized coordinate system, by doing so, the coordinate mapping is done by the drawing area automatically.
+Besides that, the drawing area also allows for a customized coordinate system, by doing so, the coordinate mapping is done by the drawing area automatically.
```rust
use plotters::prelude::*;
@@ -500,7 +498,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
### Elements
-In Plotters, elements are build blocks of figures. All elements are able to draw on a drawing area.
+In Plotters, elements are the building blocks of figures. All elements are able to be drawn on a drawing area.
There are different types of built-in elements, like lines, texts, circles, etc.
You can also define your own element in the application code.
@@ -528,9 +526,9 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
### Composable Elements
-Besides the built-in elements, elements can be composed into a logic group we called composed elements.
+Besides the built-in elements, elements can be composed into a logical group we called composed elements.
When composing new elements, the upper-left corner is given in the target coordinate, and a new pixel-based
-coordinate which has the upper-left corner defined as `(0,0)` is used for further element composition purpose.
+coordinate which has the upper-left corner defined as `(0,0)` is used for further element composition.
For example, we can have an element which includes a dot and its coordinate.
@@ -571,7 +569,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
### Chart Context
-In order to draw a chart, Plotters need a data object built on top of the drawing area called `ChartContext`.
+In order to draw a chart, Plotters needs a data object built on top of the drawing area called `ChartContext`.
The chart context defines even higher level constructs compare to the drawing area.
For example, you can define the label areas, meshes, and put a data series onto the drawing area with the help
of the chart context object.
@@ -582,7 +580,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let root = BitMapBackend::new("plotters-doc-data/5.png", (640, 480)).into_drawing_area();
root.fill(&WHITE);
let root = root.margin(10, 10, 10, 10);
- // After this point, we should be able to draw construct a chart context
+ // After this point, we should be able to construct a chart context
let mut chart = ChartBuilder::on(&root)
// Set the caption of the chart
.caption("This is our first plot", ("sans-serif", 40).into_font())
@@ -629,14 +627,14 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
### Development Version
-Find the latest development version of Plotters on [GitHub](https://github.com/38/plotters.git).
+Find the latest development version of Plotters on [GitHub](https://github.com/plotters-rs/plotters.git).
Clone the repository and learn more about the Plotters API and ways to contribute. Your help is needed!
If you want to add the development version of Plotters to your project, add the following to your `Cargo.toml`:
```toml
[dependencies]
-plotters = { git = "https://github.com/38/plotters.git" }
+plotters = { git = "https://github.com/plotters-rs/plotters.git" }
```
### Reducing Depending Libraries && Turning Off Backends
@@ -650,7 +648,7 @@ For example, the following dependency description would avoid compiling with bit
```toml
[dependencies]
-plotters = { git = "https://github.com/38/plotters.git", default_features = false, features = ["svg"] }
+plotters = { git = "https://github.com/plotters-rs/plotters.git", default_features = false, features = ["svg"] }
```
The library also allows consumers to make use of the [`Palette`](https://crates.io/crates/palette/) crate's color types by default.
@@ -663,21 +661,50 @@ Use `default_features = false` to disable those default enabled features,
and then you should be able to cherry-pick what features you want to include into `Plotters` crate.
By doing so, you can minimize the number of dependencies down to only `itertools` and compile time is less than 6s.
-The following list is a complete list of features that can be opt in and out.
+The following list is a complete list of features that can be opted in or out.
- Tier 1 drawing backends
| Name | Description | Additional Dependency |Default?|
|---------|--------------|--------|------------|
-| bitmap\_encoder | Allow `BitMapBackend` save the result to bitmap files | image, rusttype, font-kit | Yes |
+| bitmap\_encoder | Allow `BitMapBackend` to save the result to bitmap files | image, rusttype, font-kit | Yes |
| svg\_backend | Enable `SVGBackend` Support | None | Yes |
| bitmap\_gif| Opt-in GIF animation Rendering support for `BitMapBackend`, implies `bitmap` enabled | gif | Yes |
- Font manipulation features
-| Name | Description | Additional Dependency |Default?|
-|---------|--------------|--------|------------|
-| ttf | Allows TrueType font support | rusttype, font-kit | Yes |
+| Name | Description | Additional Dependency | Default? |
+|----------|------------------------------------------|-----------------------|----------|
+| ttf | Allows TrueType font support | font-kit | Yes |
+| ab_glyph | Skips loading system fonts, unlike `ttf` | ab_glyph | No |
+
+`ab_glyph` supports TrueType and OpenType fonts, but does not attempt to
+load fonts provided by the system on which it is running.
+It is pure Rust, and easier to cross compile.
+To use this, you *must* call `plotters::style::register_font` before
+using any `plotters` functions which require the ability to render text.
+This function only exists when the `ab_glyph` feature is enabled.
+```rust,ignore
+/// Register a font in the fonts table.
+///
+/// The `name` parameter gives the name this font shall be referred to
+/// in the other APIs, like `"sans-serif"`.
+///
+/// Unprovided font styles for a given name will fallback to `FontStyle::Normal`
+/// if that is available for that name, when other functions lookup fonts which
+/// are registered with this function.
+///
+/// The `bytes` parameter should be the complete contents
+/// of an OpenType font file, like:
+/// ```ignore
+/// include_bytes!("FiraGO-Regular.otf")
+/// ```
+pub fn register_font(
+ name: &str,
+ style: FontStyle,
+ bytes: &'static [u8],
+) -> Result<(), InvalidFont>
+```
- Coordinate features
@@ -715,7 +742,7 @@ The following list is a complete list of features that can be opt in and out.
* How to draw text/circle/point/rectangle/... on the top of chart ?
- As you may realized, Plotters is a drawing library rather than a traditional data plotting library,
+ As you may have realized, Plotters is a drawing library rather than a traditional data plotting library,
you have the freedom to draw anything you want on the drawing area.
Use `DrawingArea::draw` to draw any element on the drawing area.
@@ -729,10 +756,10 @@ The following list is a complete list of features that can be opt in and out.
- [HTML5 Canvas Backend](https://github.com/plotters-rs/plotters-canvas.git)
- [GTK/Cairo Backend](https://github.com/plotters-rs/plotters-cairo.git)
-* How to check if a backend writes file successfully ?
+* How to check if a backend writes to a file successfully ?
- The behavior of Plotters backend is consistent with standard library.
- When the backend instance is being dropped, [`crate::drawing::DrawingArea::present()`] or `Backend::present()` is called automatically
+ The behavior of Plotters backend is consistent with the standard library.
+ When the backend instance is dropped, [`crate::drawing::DrawingArea::present()`] or `Backend::present()` is called automatically
whenever is needed. When the `present()` method is called from `drop`, any error will be silently ignored.
In the case that error handling is important, you need manually call the `present()` method before the backend gets dropped.
@@ -825,6 +852,9 @@ pub mod prelude {
#[cfg(feature = "full_palette")]
pub use crate::style::full_palette;
+ #[cfg(feature = "colormaps")]
+ pub use crate::style::colors::colormaps::*;
+
pub use crate::style::{
AsRelative, Color, FontDesc, FontFamily, FontStyle, FontTransform, HSLColor, IntoFont,
IntoTextStyle, Palette, Palette100, Palette99, Palette9999, PaletteColor, RGBAColor,
diff --git a/src/series/line_series.rs b/src/series/line_series.rs
index 2d0cf98..448d029 100644
--- a/src/series/line_series.rs
+++ b/src/series/line_series.rs
@@ -45,8 +45,7 @@ impl<DB: DrawingBackend, Coord: Clone + 'static> Iterator for LineSeries<DB, Coo
let idx = self.point_idx;
self.point_idx += 1;
return Some(
- Circle::new(self.data[idx].clone(), self.point_size, self.style)
- .into_dyn(),
+ Circle::new(self.data[idx].clone(), self.point_size, self.style).into_dyn(),
);
}
let mut data = vec![];
diff --git a/src/style/colors/colormaps.rs b/src/style/colors/colormaps.rs
new file mode 100644
index 0000000..50430db
--- /dev/null
+++ b/src/style/colors/colormaps.rs
@@ -0,0 +1,311 @@
+use crate::style::{HSLColor, RGBAColor, RGBColor};
+
+use num_traits::{Float, FromPrimitive, ToPrimitive};
+
+/// Converts scalar values to colors.
+pub trait ColorMap<ColorType: crate::prelude::Color, FloatType = f32>
+where
+ FloatType: Float,
+{
+ /// Takes a scalar value 0.0 <= h <= 1.0 and returns the corresponding color.
+ /// Typically color-scales are named according to which color-type they return.
+ /// To use upper and lower bounds with ths function see [get_color_normalized](ColorMap::get_color_normalized).
+ fn get_color(&self, h: FloatType) -> ColorType {
+ self.get_color_normalized(h, FloatType::zero(), FloatType::one())
+ }
+
+ /// A slight abstraction over [get_color](ColorMap::get_color) function where lower and upper bound can be specified.
+ fn get_color_normalized(&self, h: FloatType, min: FloatType, max: FloatType) -> ColorType;
+}
+
+/// This struct is used to dynamically construct colormaps by giving it a slice of colors.
+/// It can then be used when being intantiated, but not with associated functions.
+/// ```
+/// use plotters::prelude::{BLACK,BLUE,WHITE,DerivedColorMap,ColorMap};
+///
+/// let derived_colormap = DerivedColorMap::new(
+/// &[BLACK,
+/// BLUE,
+/// WHITE]
+/// );
+///
+/// assert_eq!(derived_colormap.get_color(0.0), BLACK);
+/// assert_eq!(derived_colormap.get_color(0.5), BLUE);
+/// assert_eq!(derived_colormap.get_color(1.0), WHITE);
+/// ```
+pub struct DerivedColorMap<ColorType> {
+ colors: Vec<ColorType>,
+}
+
+impl<ColorType: crate::style::Color + Clone> DerivedColorMap<ColorType> {
+ /// This function lets the user define a new colormap by simply specifying colors in the correct order.
+ /// For calculation of the color values, the colors will be spaced evenly apart.
+ pub fn new(colors: &[ColorType]) -> Self {
+ DerivedColorMap {
+ colors: colors.to_vec(),
+ }
+ }
+}
+
+macro_rules! calculate_new_color_value(
+ ($relative_difference:expr, $colors:expr, $index_upper:expr, $index_lower:expr, RGBColor) => {
+ RGBColor(
+ // These equations are a very complicated way of writing a simple linear extrapolation with lots of casting between numerical values
+ // In principle every cast should be safe which is why we choose to unwrap
+ // (1.0 - r) * color_value_1 + r * color_value_2
+ ((FloatType::one() - $relative_difference) * FloatType::from_u8($colors[$index_upper].0).unwrap() + $relative_difference * FloatType::from_u8($colors[$index_lower].0).unwrap()).round().to_u8().unwrap(),
+ ((FloatType::one() - $relative_difference) * FloatType::from_u8($colors[$index_upper].1).unwrap() + $relative_difference * FloatType::from_u8($colors[$index_lower].1).unwrap()).round().to_u8().unwrap(),
+ ((FloatType::one() - $relative_difference) * FloatType::from_u8($colors[$index_upper].2).unwrap() + $relative_difference * FloatType::from_u8($colors[$index_lower].2).unwrap()).round().to_u8().unwrap()
+ )
+ };
+ ($relative_difference:expr, $colors:expr, $index_upper:expr, $index_lower:expr, RGBAColor) => {
+ RGBAColor(
+ // These equations are a very complicated way of writing a simple linear extrapolation with lots of casting between numerical values
+ // In principle every cast should be safe which is why we choose to unwrap
+ // (1.0 - r) * color_value_1 + r * color_value_2
+ ((FloatType::one() - $relative_difference) * FloatType::from_u8($colors[$index_upper].0).unwrap() + $relative_difference * FloatType::from_u8($colors[$index_lower].0).unwrap()).round().to_u8().unwrap(),
+ ((FloatType::one() - $relative_difference) * FloatType::from_u8($colors[$index_upper].1).unwrap() + $relative_difference * FloatType::from_u8($colors[$index_lower].1).unwrap()).round().to_u8().unwrap(),
+ ((FloatType::one() - $relative_difference) * FloatType::from_u8($colors[$index_upper].2).unwrap() + $relative_difference * FloatType::from_u8($colors[$index_lower].2).unwrap()).round().to_u8().unwrap(),
+ ((FloatType::one() - $relative_difference) * FloatType::from_f64($colors[$index_upper].3).unwrap() + $relative_difference * FloatType::from_f64($colors[$index_lower].3).unwrap()).to_f64().unwrap()
+ )
+ };
+ ($relative_difference:expr, $colors:expr, $index_upper:expr, $index_lower:expr, HSLColor) => {
+ HSLColor(
+ // These equations are a very complicated way of writing a simple linear extrapolation with lots of casting between numerical values
+ // In principle every cast should be safe which is why we choose to unwrap
+ // (1.0 - r) * color_value_1 + r * color_value_2
+ ((FloatType::one() - $relative_difference) * FloatType::from_f64($colors[$index_upper].0).unwrap() + $relative_difference * FloatType::from_f64($colors[$index_lower].0).unwrap()).to_f64().unwrap(),
+ ((FloatType::one() - $relative_difference) * FloatType::from_f64($colors[$index_upper].1).unwrap() + $relative_difference * FloatType::from_f64($colors[$index_lower].1).unwrap()).to_f64().unwrap(),
+ ((FloatType::one() - $relative_difference) * FloatType::from_f64($colors[$index_upper].2).unwrap() + $relative_difference * FloatType::from_f64($colors[$index_lower].2).unwrap()).to_f64().unwrap(),
+ )
+ };
+);
+
+fn calculate_relative_difference_index_lower_upper<
+ FloatType: Float + FromPrimitive + ToPrimitive,
+>(
+ h: FloatType,
+ min: FloatType,
+ max: FloatType,
+ n_colors: usize,
+) -> (FloatType, usize, usize) {
+ // Ensure that we do have a value in bounds
+ let h = num_traits::clamp(h, min, max);
+ // Next calculate a normalized value between 0.0 and 1.0
+ let t = (h - min) / (max - min);
+ let approximate_index =
+ t * (FloatType::from_usize(n_colors).unwrap() - FloatType::one()).max(FloatType::zero());
+ // Calculate which index are the two most nearest of the supplied value
+ let index_lower = approximate_index.floor().to_usize().unwrap();
+ let index_upper = approximate_index.ceil().to_usize().unwrap();
+ // Calculate the relative difference, ie. is the actual value more towards the color of index_upper or index_lower?
+ let relative_difference = approximate_index.ceil() - approximate_index;
+ (relative_difference, index_lower, index_upper)
+}
+
+macro_rules! implement_color_scale_for_derived_color_map{
+ ($($color_type:ident),+) => {
+ $(
+ impl<FloatType: Float + FromPrimitive + ToPrimitive> ColorMap<$color_type, FloatType> for DerivedColorMap<$color_type> {
+ fn get_color_normalized(&self, h: FloatType, min: FloatType, max: FloatType) -> $color_type {
+ let (
+ relative_difference,
+ index_lower,
+ index_upper
+ ) = calculate_relative_difference_index_lower_upper(
+ h,
+ min,
+ max,
+ self.colors.len()
+ );
+ // Interpolate the final color linearly
+ calculate_new_color_value!(
+ relative_difference,
+ self.colors,
+ index_upper,
+ index_lower,
+ $color_type
+ )
+ }
+ }
+ )+
+ }
+}
+
+implement_color_scale_for_derived_color_map! {RGBAColor, RGBColor, HSLColor}
+
+macro_rules! count {
+ () => (0usize);
+ ($x:tt $($xs:tt)* ) => (1usize + count!($($xs)*));
+}
+
+macro_rules! define_colors_from_list_of_values_or_directly{
+ ($color_type:ident, $(($($color_value:expr),+)),+) => {
+ [$($color_type($($color_value),+)),+]
+ };
+ ($($color_complete:tt),+) => {
+ [$($color_complete),+]
+ };
+}
+
+macro_rules! implement_linear_interpolation_color_map {
+ ($color_scale_name:ident, $color_type:ident) => {
+ impl<FloatType: std::fmt::Debug + Float + FromPrimitive + ToPrimitive>
+ ColorMap<$color_type, FloatType> for $color_scale_name
+ {
+ fn get_color_normalized(
+ &self,
+ h: FloatType,
+ min: FloatType,
+ max: FloatType,
+ ) -> $color_type {
+ let (
+ relative_difference,
+ index_lower,
+ index_upper
+ ) = calculate_relative_difference_index_lower_upper(
+ h,
+ min,
+ max,
+ Self::COLORS.len()
+ );
+ // Interpolate the final color linearly
+ calculate_new_color_value!(
+ relative_difference,
+ Self::COLORS,
+ index_upper,
+ index_lower,
+ $color_type
+ )
+ }
+ }
+
+ impl $color_scale_name {
+ #[doc = "Get color value from `"]
+ #[doc = stringify!($color_scale_name)]
+ #[doc = "` by supplying a parameter 0.0 <= h <= 1.0"]
+ pub fn get_color<FloatType: std::fmt::Debug + Float + FromPrimitive + ToPrimitive>(
+ h: FloatType,
+ ) -> $color_type {
+ let color_scale = $color_scale_name {};
+ color_scale.get_color(h)
+ }
+
+ #[doc = "Get color value from `"]
+ #[doc = stringify!($color_scale_name)]
+ #[doc = "` by supplying lower and upper bounds min, max and a parameter h where min <= h <= max"]
+ pub fn get_color_normalized<
+ FloatType: std::fmt::Debug + Float + FromPrimitive + ToPrimitive,
+ >(
+ h: FloatType,
+ min: FloatType,
+ max: FloatType,
+ ) -> $color_type {
+ let color_scale = $color_scale_name {};
+ color_scale.get_color_normalized(h, min, max)
+ }
+ }
+ };
+}
+
+#[macro_export]
+/// Macro to create a new colormap with evenly spaced colors at compile-time.
+macro_rules! define_linear_interpolation_color_map{
+ ($color_scale_name:ident, $color_type:ident, $doc:expr, $(($($color_value:expr),+)),*) => {
+ #[doc = $doc]
+ pub struct $color_scale_name {}
+
+ impl $color_scale_name {
+ // const COLORS: [$color_type; $number_colors] = [$($color_type($($color_value),+)),+];
+ // const COLORS: [$color_type; count!($(($($color_value:expr),+))*)] = [$($color_type($($color_value),+)),+];
+ const COLORS: [$color_type; count!($(($($color_value:expr),+))*)] = define_colors_from_list_of_values_or_directly!{$color_type, $(($($color_value),+)),*};
+ }
+
+ implement_linear_interpolation_color_map!{$color_scale_name, $color_type}
+ };
+ ($color_scale_name:ident, $color_type:ident, $doc:expr, $($color_complete:tt),+) => {
+ #[doc = $doc]
+ pub struct $color_scale_name {}
+
+ impl $color_scale_name {
+ const COLORS: [$color_type; count!($($color_complete)*)] = define_colors_from_list_of_values_or_directly!{$($color_complete),+};
+ }
+
+ implement_linear_interpolation_color_map!{$color_scale_name, $color_type}
+ }
+}
+
+define_linear_interpolation_color_map! {
+ ViridisRGBA,
+ RGBAColor,
+ "A colormap optimized for visually impaired people (RGBA format).
+ It is currently the default colormap also used by [matplotlib](https://matplotlib.org/stable/tutorials/colors/colormaps.html).
+ Read more in this [paper](https://doi.org/10.1371/journal.pone.0199239)",
+ ( 68, 1, 84, 1.0),
+ ( 70, 50, 127, 1.0),
+ ( 54, 92, 141, 1.0),
+ ( 39, 127, 143, 1.0),
+ ( 31, 162, 136, 1.0),
+ ( 74, 194, 110, 1.0),
+ (160, 219, 57, 1.0),
+ (254, 232, 37, 1.0)
+}
+
+define_linear_interpolation_color_map! {
+ ViridisRGB,
+ RGBColor,
+ "A colormap optimized for visually impaired people (RGB Format).
+ It is currently the default colormap also used by [matplotlib](https://matplotlib.org/stable/tutorials/colors/colormaps.html).
+ Read more in this [paper](https://doi.org/10.1371/journal.pone.0199239)",
+ ( 68, 1, 84),
+ ( 70, 50, 127),
+ ( 54, 92, 141),
+ ( 39, 127, 143),
+ ( 31, 162, 136),
+ ( 74, 194, 110),
+ (160, 219, 57),
+ (254, 232, 37)
+}
+
+define_linear_interpolation_color_map! {
+ BlackWhite,
+ RGBColor,
+ "Simple chromatic colormap from black to white.",
+ ( 0, 0, 0),
+ (255, 255, 255)
+}
+
+define_linear_interpolation_color_map! {
+ MandelbrotHSL,
+ HSLColor,
+ "Colormap created to replace the one used in the mandelbrot example.",
+ (0.0, 1.0, 0.5),
+ (1.0, 1.0, 0.5)
+}
+
+define_linear_interpolation_color_map! {
+ VulcanoHSL,
+ HSLColor,
+ "A vulcanic colormap that display red/orange and black colors",
+ (2.0/3.0, 1.0, 0.7),
+ ( 0.0, 1.0, 0.7)
+}
+
+use super::full_palette::*;
+define_linear_interpolation_color_map! {
+ Bone,
+ RGBColor,
+ "Dark colormap going from black over blue to white.",
+ BLACK,
+ BLUE,
+ WHITE
+}
+
+define_linear_interpolation_color_map! {
+ Copper,
+ RGBColor,
+ "Friendly black to brown colormap.",
+ BLACK,
+ BROWN,
+ ORANGE
+}
diff --git a/src/style/colors/mod.rs b/src/style/colors/mod.rs
index 34448ba..8aa09a7 100644
--- a/src/style/colors/mod.rs
+++ b/src/style/colors/mod.rs
@@ -1,8 +1,9 @@
//! Basic predefined colors.
use super::{RGBAColor, RGBColor};
-// Macro for allowing dynamic creation of doc attributes.
// Taken from https://stackoverflow.com/questions/60905060/prevent-line-break-in-doc-test
+/// Macro for allowing dynamic creation of doc attributes.
+#[macro_export]
macro_rules! doc {
{
$(#[$m:meta])*
@@ -55,5 +56,10 @@ define_color!(CYAN, 0, 255, 255, "Cyan");
define_color!(MAGENTA, 255, 0, 255, "Magenta");
define_color!(TRANSPARENT, 0, 0, 0, 0.0, "Transparent");
+#[cfg(feature = "colormaps")]
+/// Colormaps can be used to simply go from a scalar value to a color value which will be more/less
+/// intense corresponding to the value of the supplied scalar.
+/// These colormaps can also be defined by the user and be used with lower and upper bounds.
+pub mod colormaps;
#[cfg(feature = "full_palette")]
pub mod full_palette;
diff --git a/src/style/font/ab_glyph.rs b/src/style/font/ab_glyph.rs
new file mode 100644
index 0000000..42b4334
--- /dev/null
+++ b/src/style/font/ab_glyph.rs
@@ -0,0 +1,160 @@
+use super::{FontData, FontFamily, FontStyle, LayoutBox};
+use ab_glyph::{Font, FontRef, ScaleFont};
+use core::fmt::{self, Display};
+use once_cell::sync::Lazy;
+use std::collections::HashMap;
+use std::error::Error;
+use std::sync::RwLock;
+
+struct FontMap {
+ map: HashMap<String, FontRef<'static>>,
+}
+impl FontMap {
+ fn new() -> Self {
+ Self {
+ map: HashMap::with_capacity(4),
+ }
+ }
+ fn insert(&mut self, style: FontStyle, font: FontRef<'static>) -> Option<FontRef<'static>> {
+ self.map.insert(style.as_str().to_string(), font)
+ }
+ // fn get(&self, style: FontStyle) -> Option<&FontRef<'static>> {
+ // self.map.get(style.as_str())
+ // }
+ fn get_fallback(&self, style: FontStyle) -> Option<&FontRef<'static>> {
+ self.map
+ .get(style.as_str())
+ .or_else(|| self.map.get(FontStyle::Normal.as_str()))
+ }
+}
+
+static FONTS: Lazy<RwLock<HashMap<String, FontMap>>> = Lazy::new(|| RwLock::new(HashMap::new()));
+pub struct InvalidFont {
+ _priv: (),
+}
+
+// Note for future contributors: There is nothing fundamental about the static reference requirement here.
+// It would be reasonably easy to add a function which accepts an owned buffer,
+// or even a reference counted buffer, instead.
+/// Register a font in the fonts table.
+///
+/// The `name` parameter gives the name this font shall be referred to
+/// in the other APIs, like `"sans-serif"`.
+///
+/// Unprovided font styles for a given name will fallback to `FontStyle::Normal`
+/// if that is available for that name, when other functions lookup fonts which
+/// are registered with this function.
+///
+/// The `bytes` parameter should be the complete contents
+/// of an OpenType font file, like:
+/// ```ignore
+/// include_bytes!("FiraGO-Regular.otf")
+/// ```
+pub fn register_font(
+ name: &str,
+ style: FontStyle,
+ bytes: &'static [u8],
+) -> Result<(), InvalidFont> {
+ let font = FontRef::try_from_slice(bytes).map_err(|_| InvalidFont { _priv: () })?;
+ let mut lock = FONTS.write().unwrap();
+ lock.entry(name.to_string())
+ .or_insert_with(FontMap::new)
+ .insert(style, font);
+ Ok(())
+}
+
+#[derive(Clone)]
+pub struct FontDataInternal {
+ font_ref: FontRef<'static>,
+}
+
+#[derive(Debug, Clone)]
+pub enum FontError {
+ /// No idea what the problem is
+ Unknown,
+ /// No font data available for the requested family and style.
+ FontUnavailable,
+}
+impl Display for FontError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ // Since it makes literally no difference to how we'd format
+ // this, just delegate to the derived Debug formatter.
+ write!(f, "{:?}", self)
+ }
+}
+impl Error for FontError {}
+
+impl FontData for FontDataInternal {
+ // TODO: can we rename this to `Error`?
+ type ErrorType = FontError;
+ fn new(family: FontFamily<'_>, style: FontStyle) -> Result<Self, Self::ErrorType> {
+ Ok(Self {
+ font_ref: FONTS
+ .read()
+ .unwrap()
+ .get(family.as_str())
+ .and_then(|fam| fam.get_fallback(style))
+ .ok_or(FontError::FontUnavailable)?
+ .clone(),
+ })
+ }
+ // TODO: ngl, it makes no sense that this uses the same error type as `new`
+ fn estimate_layout(&self, size: f64, text: &str) -> Result<LayoutBox, Self::ErrorType> {
+ let pixel_per_em = size / 1.24;
+ // let units_per_em = self.font_ref.units_per_em().unwrap();
+ let font = self.font_ref.as_scaled(size as f32);
+
+ let mut x_pixels = 0f32;
+
+ let mut prev = None;
+ for c in text.chars() {
+ let glyph_id = font.glyph_id(c);
+ let size = font.h_advance(glyph_id);
+ x_pixels += size;
+ if let Some(pc) = prev {
+ x_pixels += font.kern(pc, glyph_id);
+ }
+ prev = Some(glyph_id);
+ }
+
+ Ok(((0, 0), (x_pixels as i32, pixel_per_em as i32)))
+ }
+ fn draw<E, DrawFunc: FnMut(i32, i32, f32) -> Result<(), E>>(
+ &self,
+ pos: (i32, i32),
+ size: f64,
+ text: &str,
+ mut draw: DrawFunc,
+ ) -> Result<Result<(), E>, Self::ErrorType> {
+ let font = self.font_ref.as_scaled(size as f32);
+ let mut draw = |x: i32, y: i32, c| {
+ let (base_x, base_y) = pos;
+ draw(base_x + x, base_y + y, c)
+ };
+ let mut x_shift = 0f32;
+ let mut prev = None;
+ for c in text.chars() {
+ if let Some(pc) = prev {
+ x_shift += font.kern(font.glyph_id(pc), font.glyph_id(c));
+ }
+ prev = Some(c);
+ let glyph = font.scaled_glyph(c);
+ if let Some(q) = font.outline_glyph(glyph) {
+ let rect = q.px_bounds();
+ let y_shift = ((size as f32) / 2.0 + rect.min.y) as i32;
+ let x_shift = x_shift as i32;
+ let mut buf = vec![];
+ q.draw(|x, y, c| buf.push((x, y, c)));
+ for (x, y, c) in buf {
+ draw(x as i32 + x_shift, y as i32 + y_shift, c).map_err(|_e| {
+ // Note: If ever `plotters` adds a tracing or logging crate,
+ // this would be a good place to use it.
+ FontError::Unknown
+ })?;
+ }
+ }
+ x_shift += font.h_advance(font.glyph_id(c));
+ }
+ Ok(Ok(()))
+ }
+}
diff --git a/src/style/font/mod.rs b/src/style/font/mod.rs
index 305978f..d80ee28 100644
--- a/src/style/font/mod.rs
+++ b/src/style/font/mod.rs
@@ -18,13 +18,35 @@ mod ttf;
use ttf::FontDataInternal;
#[cfg(all(
- not(all(target_arch = "wasm32", not(target_os = "wasi"))),
+ not(target_arch = "wasm32"),
+ not(target_os = "wasi"),
+ feature = "ab_glyph"
+))]
+mod ab_glyph;
+#[cfg(all(
+ not(target_arch = "wasm32"),
+ not(target_os = "wasi"),
+ feature = "ab_glyph"
+))]
+pub use self::ab_glyph::register_font;
+#[cfg(all(
+ not(target_arch = "wasm32"),
+ not(target_os = "wasi"),
+ feature = "ab_glyph",
not(feature = "ttf")
))]
+use self::ab_glyph::FontDataInternal;
+
+#[cfg(all(
+ not(all(target_arch = "wasm32", not(target_os = "wasi"))),
+ not(feature = "ttf"),
+ not(feature = "ab_glyph")
+))]
mod naive;
#[cfg(all(
not(all(target_arch = "wasm32", not(target_os = "wasi"))),
- not(feature = "ttf")
+ not(feature = "ttf"),
+ not(feature = "ab_glyph")
))]
use naive::FontDataInternal;
diff --git a/src/style/font/ttf.rs b/src/style/font/ttf.rs
index e6feadc..345aae4 100644
--- a/src/style/font/ttf.rs
+++ b/src/style/font/ttf.rs
@@ -82,9 +82,7 @@ impl FontExt {
_ => unreachable!(),
};
let face = unsafe {
- std::mem::transmute::<_, Option<Face<'static>>>(
- ttf_parser::Face::from_slice(data, idx).ok(),
- )
+ std::mem::transmute::<_, Option<Face<'static>>>(ttf_parser::Face::parse(data, idx).ok())
};
Self { inner: font, face }
}
diff --git a/src/style/mod.rs b/src/style/mod.rs
index 7d7c9ac..4daa0a8 100644
--- a/src/style/mod.rs
+++ b/src/style/mod.rs
@@ -17,9 +17,12 @@ pub use colors::{BLACK, BLUE, CYAN, GREEN, MAGENTA, RED, TRANSPARENT, WHITE, YEL
#[cfg(feature = "full_palette")]
pub use colors::full_palette;
+#[cfg(all(not(target_arch = "wasm32"), feature = "ab_glyph"))]
+pub use font::register_font;
pub use font::{
FontDesc, FontError, FontFamily, FontResult, FontStyle, FontTransform, IntoFont, LayoutBox,
};
+
pub use shape::ShapeStyle;
pub use size::{AsRelative, RelativeSize, SizeDesc};
pub use text::text_anchor;