diff --git a/.gitignore b/.gitignore index c6695f5e..269016ca 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ **/target .vscode/* Cargo.lock +.idea diff --git a/CHANGELOG.md b/CHANGELOG.md index 86186ab4..be9630ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,27 @@ # Changelog -## Plotters 0.3.4 (?) +## Plotters 0.3.5 (2023-06-16) + +### Added + +- Add ab_glyph font backend +- Color maps + +### Fixed + +- Fix broken unaligned read in unsafe code +- A lot of broken links and typos + +## Plotters 0.3.4 (2022-09-08) + +### Fixed + +- EvcxR feature compiling issue without bitmap backend enabled + +### Improved + +- Color types manipulations + ## Plotters 0.3.3 (2022-08-19) diff --git a/README.md b/README.md index fa451ddd..449efdc7 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 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 🦀📈🚀 @@ -13,33 +13,33 @@ -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 To view the source code for each example, please click on the example image. - + - + - + - + @@ -47,84 +47,84 @@ To view the source code for each example, please click on the example image. - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + @@ -140,8 +140,8 @@ To view the source code for each example, please click on the example image. * [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) @@ -163,7 +163,7 @@ To view the source code for each example, please click on the example image. 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`, @@ -206,7 +206,7 @@ fn main() -> Result<(), Box> { ## 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) @@ -215,13 +215,13 @@ To learn how to use Plotters in different scenarios by checking out the followin ## 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::*; @@ -256,7 +256,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. @@ -266,57 +266,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::*; @@ -335,10 +333,10 @@ fn main() -> Result<(), Box> { ### 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::*; @@ -360,7 +358,7 @@ fn main() -> Result<(), Box> { ### 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. @@ -388,9 +386,9 @@ fn main() -> Result<(), Box> { ### 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. @@ -431,7 +429,7 @@ fn main() -> Result<(), Box> { ### 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. @@ -442,7 +440,7 @@ fn main() -> Result<(), Box> { 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()) @@ -489,14 +487,14 @@ fn main() -> Result<(), Box> { ### 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 @@ -510,7 +508,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. @@ -523,21 +521,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 @@ -575,7 +602,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. @@ -589,10 +616,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. diff --git a/doc-template/examples/chart.rs b/doc-template/examples/chart.rs index a8422c02..46a8455b 100644 --- a/doc-template/examples/chart.rs +++ b/doc-template/examples/chart.rs @@ -3,7 +3,7 @@ fn main() -> Result<(), Box> { 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()) diff --git a/doc-template/readme.template.md b/doc-template/readme.template.md index eaa96c8b..e4f081e7 100644 --- a/doc-template/readme.template.md +++ b/doc-template/readme.template.md @@ -1,4 +1,4 @@ -# 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 🦀📈🚀 @@ -13,14 +13,14 @@ -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 @@ -54,27 +54,27 @@ $$../examples/quick_start.rs$$ ## 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 = { git = "https://github.com/plotters-rs/plotters", default_features = false, features = ["evcxr"] } 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) @@ -104,7 +104,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. @@ -114,57 +114,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 $$../examples/drawing_backends.rs$$ @@ -174,10 +172,10 @@ $$../examples/drawing_backends.rs$$ ### 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 $$../examples/drawing_area.rs$$ @@ -187,7 +185,7 @@ $$../examples/drawing_area.rs$$ ### 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. @@ -203,9 +201,9 @@ $$../examples/elements.rs$$ ### 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. @@ -217,7 +215,7 @@ $$../examples/composable_elements.rs$$ ### 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. @@ -232,14 +230,14 @@ $$../examples/chart.rs$$ ### 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 @@ -253,7 +251,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. @@ -266,21 +264,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 @@ -318,7 +345,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. @@ -332,10 +359,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. diff --git a/doc-template/readme/gallery b/doc-template/readme/gallery index c47d54c7..79105f71 100644 --- a/doc-template/readme/gallery +++ b/doc-template/readme/gallery @@ -1,18 +1,18 @@ To view the source code for each example, please click on the example image. - + - + - + - + @@ -20,83 +20,83 @@ To view the source code for each example, please click on the example image. - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + diff --git a/doc-template/rustdoc/gallery b/doc-template/rustdoc/gallery index af378211..b1f64fe3 100644 --- a/doc-template/rustdoc/gallery +++ b/doc-template/rustdoc/gallery @@ -4,7 +4,7 @@
Multiple Plot - [code] + [code]
@@ -14,7 +14,7 @@
Candlestick Plot - [code] + [code]
@@ -24,7 +24,7 @@
Histogram - [code] + [code]
@@ -52,7 +52,7 @@
Mandelbrot set - [code] + [code]
@@ -72,7 +72,7 @@
Real-time Rendering - [code] + [code]
@@ -82,7 +82,7 @@
Histogram with Scatter - [code] + [code]
@@ -92,7 +92,7 @@
Dual Y-Axis Example - [code] + [code]
@@ -102,7 +102,7 @@
The Matplotlib Matshow Example - [code] + [code]
@@ -112,7 +112,7 @@
The Sierpinski Carpet - [code] + [code]
@@ -122,7 +122,7 @@
The 1D Gaussian Distribution - [code] + [code]
@@ -132,7 +132,7 @@
The 1D Gaussian Distribution - [code] + [code]
@@ -142,7 +142,7 @@
Monthly Time Coordinate - [code] + [code]
@@ -152,7 +152,7 @@
Monthly Time Coordinate - [code] + [code]
@@ -162,7 +162,7 @@
Koch Snowflake - [code] + [code]
@@ -173,7 +173,7 @@
Koch Snowflake Animation - [code] + [code]
@@ -184,7 +184,7 @@
Drawing on a Console - [code] + [code]
@@ -194,7 +194,7 @@
Drawing bitmap on chart - [code] + [code]
@@ -204,7 +204,7 @@
The boxplot demo - [code] + [code]
@@ -214,7 +214,7 @@
3D plot rendering - [code] + [code]
@@ -224,7 +224,7 @@
2-Var Gussian Distribution PDF - [code] + [code]
@@ -234,6 +234,6 @@
COVID-19 Visualization - [code] + [code]
diff --git a/doc-template/update_readme.sh b/doc-template/update_readme.sh index f606ac27..0cc3fd89 100755 --- a/doc-template/update_readme.sh +++ b/doc-template/update_readme.sh @@ -1,4 +1,5 @@ #!/bin/bash +set -ev REPO_BASE=`readlink -f $(dirname $(readlink -f $0))/../` ${REPO_BASE}/doc-template/render_readme.sh ${REPO_BASE}/doc-template/readme.template.md ${REPO_BASE}/doc-template/readme > ${REPO_BASE}/README.md diff --git a/plotters-backend/Cargo.toml b/plotters-backend/Cargo.toml index 9a2ba856..c3aa8cbb 100644 --- a/plotters-backend/Cargo.toml +++ b/plotters-backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "plotters-backend" -version = "0.3.4" +version = "0.3.5" authors = ["Hao Hou "] edition = "2018" license = "MIT" diff --git a/plotters-backend/LICENSE b/plotters-backend/LICENSE new file mode 120000 index 00000000..ea5b6064 --- /dev/null +++ b/plotters-backend/LICENSE @@ -0,0 +1 @@ +../LICENSE \ No newline at end of file diff --git a/plotters-backend/README.md b/plotters-backend/README.md index dc7720b4..871fc7ce 100644 --- a/plotters-backend/README.md +++ b/plotters-backend/README.md @@ -3,6 +3,6 @@ This is a part of plotters project. For more details, please check the following links: - For high-level intro of Plotters, see: [Plotters on crates.io](https://crates.io/crates/plotters) -- Check the main repo at [Plotters repo](https://github.com/38/plotters.git) +- Check the main repo at [Plotters repo](https://github.com/plotters-rs/plotters.git) - For detailed documentation about this crate, check [plotters-backend on docs.rs](https://docs.rs/plotters-backend/) - You can also visit Plotters [Homepage](https://plotters-rs.github.io) diff --git a/plotters-backend/src/lib.rs b/plotters-backend/src/lib.rs index d4fd904c..6d4ebe08 100644 --- a/plotters-backend/src/lib.rs +++ b/plotters-backend/src/lib.rs @@ -33,7 +33,7 @@ ```text .ensure_prepared() && +-------------+ +-------------+ .draw_pixels() +--------------+ drop - |Start drwaing|--->|Ready to draw| ------------------------+---->|Finish 1 frame| ---------> + |Start drawing|--->|Ready to draw| ------------------------+---->|Finish 1 frame| ---------> +-------------+ +-------------+ | +--------------+ ^ ^ | | | +------------------------------- + | @@ -235,12 +235,14 @@ pub trait DrawingBackend: Sized { let ((min_x, min_y), (max_x, max_y)) = layout; let width = (max_x - min_x) as i32; let height = (max_y - min_y) as i32; - let dx = match style.anchor().h_pos { + + let anchor = style.anchor().unwrap_or_default(); + let dx = match anchor.h_pos { HPos::Left => 0, HPos::Right => -width, HPos::Center => -width / 2, }; - let dy = match style.anchor().v_pos { + let dy = match anchor.v_pos { VPos::Top => 0, VPos::Center => -height / 2, VPos::Bottom => -height, @@ -308,9 +310,9 @@ pub trait DrawingBackend: Sized { break; } // FIXME: This assume we have RGB image buffer - let r = src[(dx + dy * w) as usize * 3]; - let g = src[(dx + dy * w) as usize * 3 + 1]; - let b = src[(dx + dy * w) as usize * 3 + 2]; + let r = src[(dx + dy * iw) as usize * 3]; + let g = src[(dx + dy * iw) as usize * 3 + 1]; + let b = src[(dx + dy * iw) as usize * 3 + 2]; let color = BackendColor { alpha: 1.0, rgb: (r, g, b), diff --git a/plotters-backend/src/rasterizer/mod.rs b/plotters-backend/src/rasterizer/mod.rs index d322391e..b475acd2 100644 --- a/plotters-backend/src/rasterizer/mod.rs +++ b/plotters-backend/src/rasterizer/mod.rs @@ -10,7 +10,7 @@ // the question mark operator has a huge performance impact due to LLVM unable to handle it. // So the question is if this trick is still useful, or LLVM is smart enough to handle it since // then. -// +// // -- // Original comment: // diff --git a/plotters-backend/src/rasterizer/path.rs b/plotters-backend/src/rasterizer/path.rs index 35ae6049..eae0bfe2 100644 --- a/plotters-backend/src/rasterizer/path.rs +++ b/plotters-backend/src/rasterizer/path.rs @@ -34,8 +34,8 @@ fn compute_polygon_vertex(triple: &[BackendCoord; 3], d: f64, buf: &mut Vec From<&'a str> for FontFamily<'a> { /// ``` pub mod text_anchor { /// The horizontal position of the anchor point relative to the text. - #[derive(Clone, Copy)] + #[derive(Clone, Copy, Default)] pub enum HPos { /// Anchor point is on the left side of the text + #[default] Left, /// Anchor point is on the right side of the text Right, @@ -71,9 +72,10 @@ pub mod text_anchor { } /// The vertical position of the anchor point relative to the text. - #[derive(Clone, Copy)] + #[derive(Clone, Copy, Default)] pub enum VPos { /// Anchor point is on the top of the text + #[default] Top, /// Anchor point is in the vertical center of the text Center, @@ -82,7 +84,7 @@ pub mod text_anchor { } /// The text anchor position. - #[derive(Clone, Copy)] + #[derive(Clone, Copy, Default)] pub struct Pos { /// The horizontal position of the anchor point pub h_pos: HPos, @@ -105,22 +107,6 @@ pub mod text_anchor { pub fn new(h_pos: HPos, v_pos: VPos) -> Self { Pos { h_pos, v_pos } } - - /// Create a default text anchor position (top left). - /// - /// - **returns** The default text anchor position - /// - /// ```rust - /// use plotters_backend::text_anchor::{Pos, HPos, VPos}; - /// - /// let pos = Pos::default(); - /// ``` - pub fn default() -> Self { - Pos { - h_pos: HPos::Left, - v_pos: VPos::Top, - } - } } } @@ -227,8 +213,8 @@ pub trait BackendTextStyle { FontStyle::Normal } - fn anchor(&self) -> text_anchor::Pos { - text_anchor::Pos::default() + fn anchor(&self) -> Option { + None } fn family(&self) -> FontFamily; diff --git a/plotters-bitmap/Cargo.toml b/plotters-bitmap/Cargo.toml index 6a48bc08..3cedf88a 100644 --- a/plotters-bitmap/Cargo.toml +++ b/plotters-bitmap/Cargo.toml @@ -12,9 +12,10 @@ readme = "README.md" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -gif = { version = "0.11.2", optional = true } +gif = { version = "0.12.0", optional = true } [dependencies.plotters-backend] +version = "0.3.5" path = "../plotters-backend" [target.'cfg(not(target_arch = "wasm32"))'.dependencies.image] @@ -34,7 +35,7 @@ features = ["ttf", "line_series", "bitmap_backend"] path = "../plotters" [dev-dependencies] -criterion = "0.3.6" +criterion = "0.4.0" rayon = "1.5.1" [[bench]] diff --git a/plotters-bitmap/LICENSE b/plotters-bitmap/LICENSE new file mode 120000 index 00000000..ea5b6064 --- /dev/null +++ b/plotters-bitmap/LICENSE @@ -0,0 +1 @@ +../LICENSE \ No newline at end of file diff --git a/plotters-bitmap/README.md b/plotters-bitmap/README.md index 7cafc54a..65099ff4 100644 --- a/plotters-bitmap/README.md +++ b/plotters-bitmap/README.md @@ -3,6 +3,6 @@ This is a part of plotters project. For more details, please check the following links: - For high-level intro of Plotters, see: [Plotters on crates.io](https://crates.io/crates/plotters) -- Check the main repo at [Plotters repo](https://github.com/38/plotters.git) +- Check the main repo at [Plotters repo](https://github.com/plotters-rs/plotters.git) - For detailed documentation about this crate, check [plotters-backend on docs.rs](https://docs.rs/plotters-backend/) - You can also visit Plotters [Homepage](https://plotters-rs.github.io) diff --git a/plotters-bitmap/src/bitmap.rs b/plotters-bitmap/src/bitmap.rs index 05b22ede..39d23bf3 100644 --- a/plotters-bitmap/src/bitmap.rs +++ b/plotters-bitmap/src/bitmap.rs @@ -91,7 +91,7 @@ impl<'a> BitMapBackend<'a, RGBPixel> { /// Create a new bitmap backend which only lives in-memory /// - /// When this is used, the bitmap backend will write to a user provided [u8] array (or Vec) + /// When this is used, the bitmap backend will write to a user provided [u8] array (or `Vec`) /// in RGB pixel format. /// /// Note: This function provides backward compatibility for those code that assumes Plotters diff --git a/plotters-bitmap/src/bitmap_pixel/bgrx.rs b/plotters-bitmap/src/bitmap_pixel/bgrx.rs index 16bcd25e..2f90d9d5 100644 --- a/plotters-bitmap/src/bitmap_pixel/bgrx.rs +++ b/plotters-bitmap/src/bitmap_pixel/bgrx.rs @@ -87,7 +87,7 @@ impl PixelFormat for BGRXPixel { let slice = unsafe { std::slice::from_raw_parts_mut(start_ptr, (count - 1) / 2) }; for rp in slice.iter_mut() { let ptr = rp as *mut [u8; 8] as *mut u64; - let d1 = unsafe { *ptr }; + let d1 = unsafe { ptr.read_unaligned() }; let mut h = (d1 >> 8) & M; let mut l = d1 & M; @@ -104,7 +104,7 @@ impl PixelFormat for BGRXPixel { } unsafe { - *ptr = h | l; + ptr.write_unaligned(h | l); } } @@ -196,7 +196,7 @@ impl PixelFormat for BGRXPixel { let d: u64 = std::mem::transmute([ b, g, r, 0, b, g, r, 0, // QW1 ]); - *ptr = d; + ptr.write_unaligned(d); } } diff --git a/plotters-bitmap/src/bitmap_pixel/rgb.rs b/plotters-bitmap/src/bitmap_pixel/rgb.rs index e8b88216..39b3f502 100644 --- a/plotters-bitmap/src/bitmap_pixel/rgb.rs +++ b/plotters-bitmap/src/bitmap_pixel/rgb.rs @@ -67,7 +67,7 @@ impl PixelFormat for RGBPixel { // Since we should always make sure the RGB payload occupies the logic lower bits // thus, this type purning should work for both LE and BE CPUs #[rustfmt::skip] - let (p1, p2, p3): (u64, u64, u64) = unsafe { + let [p1, p2, p3]: [u64; 3] = unsafe { std::mem::transmute([ u16::from(r), u16::from(b), u16::from(g), u16::from(r), // QW1 u16::from(b), u16::from(g), u16::from(r), u16::from(b), // QW2 @@ -76,7 +76,7 @@ impl PixelFormat for RGBPixel { }; #[rustfmt::skip] - let (q1, q2, q3): (u64, u64, u64) = unsafe { + let [q1, q2, q3]: [u64; 3] = unsafe { std::mem::transmute([ u16::from(g), u16::from(r), u16::from(b), u16::from(g), // QW1 u16::from(r), u16::from(b), u16::from(g), u16::from(r), // QW2 @@ -94,8 +94,8 @@ impl PixelFormat for RGBPixel { let start_ptr = &mut dst[start * Self::PIXEL_SIZE] as *mut u8 as *mut [u8; 24]; let slice = unsafe { std::slice::from_raw_parts_mut(start_ptr, (count - 1) / 8) }; for p in slice.iter_mut() { - let ptr = p as *mut [u8; 24] as *mut (u64, u64, u64); - let (d1, d2, d3) = unsafe { *ptr }; + let ptr = p as *mut [u8; 24] as *mut [u64; 3]; + let [d1, d2, d3] = unsafe { ptr.read_unaligned() }; let (mut h1, mut h2, mut h3) = ((d1 >> 8) & M, (d2 >> 8) & M, (d3 >> 8) & M); let (mut l1, mut l2, mut l3) = (d1 & M, d2 & M, d3 & M); @@ -120,7 +120,7 @@ impl PixelFormat for RGBPixel { } unsafe { - *ptr = (h1 | l1, h2 | l2, h3 | l3); + ptr.write_unaligned([h1 | l1, h2 | l2, h3 | l3]); } } @@ -207,14 +207,14 @@ impl PixelFormat for RGBPixel { // TODO: Consider using AVX instructions when possible let ptr = p as *mut [u8; 24] as *mut u64; unsafe { - let (d1, d2, d3): (u64, u64, u64) = std::mem::transmute([ + let [d1, d2, d3]: [u64; 3] = std::mem::transmute([ r, g, b, r, g, b, r, g, // QW1 b, r, g, b, r, g, b, r, // QW2 g, b, r, g, b, r, g, b, // QW3 ]); - *ptr = d1; - *ptr.offset(1) = d2; - *ptr.offset(2) = d3; + ptr.write_unaligned(d1); + ptr.offset(1).write_unaligned(d2); + ptr.offset(2).write_unaligned(d3); } } diff --git a/plotters-svg/Cargo.toml b/plotters-svg/Cargo.toml index 30cd37e6..cd1e6d4f 100644 --- a/plotters-svg/Cargo.toml +++ b/plotters-svg/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "plotters-svg" -version = "0.3.4" +version = "0.3.5" authors = ["Hao Hou "] edition = "2018" license = "MIT" @@ -12,6 +12,7 @@ readme = "README.md" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies.plotters-backend] +version = "0.3.5" path = "../plotters-backend" [dependencies.image] diff --git a/plotters-svg/LICENSE b/plotters-svg/LICENSE new file mode 120000 index 00000000..ea5b6064 --- /dev/null +++ b/plotters-svg/LICENSE @@ -0,0 +1 @@ +../LICENSE \ No newline at end of file diff --git a/plotters-svg/README.md b/plotters-svg/README.md index 41b18b23..0d38126d 100644 --- a/plotters-svg/README.md +++ b/plotters-svg/README.md @@ -3,6 +3,6 @@ This is a part of plotters project. For more details, please check the following links: - For high-level intro of Plotters, see: [Plotters on crates.io](https://crates.io/crates/plotters) -- Check the main repo at [Plotters repo](https://github.com/38/plotters.git) +- Check the main repo at [Plotters repo](https://github.com/plotters-rs/plotters.git) - For detailed documentation about this crate, check [plotters-backend on docs.rs](https://docs.rs/plotters-backend/) - You can also visit Plotters [Homepage](https://plotters-rs.github.io) diff --git a/plotters-svg/src/svg.rs b/plotters-svg/src/svg.rs index 43bf36a2..6fd6448e 100644 --- a/plotters-svg/src/svg.rs +++ b/plotters-svg/src/svg.rs @@ -8,12 +8,12 @@ use plotters_backend::{ FontStyle, FontTransform, }; +use std::fmt::Write as _; use std::fs::File; #[allow(unused_imports)] use std::io::Cursor; use std::io::{BufWriter, Error, Write}; use std::path::Path; -use std::fmt::Write as _; fn make_svg_color(color: BackendColor) -> String { let (r, g, b) = color.rgb; @@ -394,13 +394,14 @@ impl<'a> DrawingBackend for SVGBackend<'a> { } let (x0, y0) = pos; - let text_anchor = match style.anchor().h_pos { + let anchor = style.anchor().unwrap_or_default(); + let text_anchor = match anchor.h_pos { HPos::Left => "start", HPos::Right => "end", HPos::Center => "middle", }; - let dy = match style.anchor().v_pos { + let dy = match anchor.v_pos { VPos::Top => "0.76em", VPos::Center => "0.5ex", VPos::Bottom => "-0.5ex", @@ -410,12 +411,12 @@ impl<'a> DrawingBackend for SVGBackend<'a> { { let ((fx0, fy0), (fx1, fy1)) = font.layout_box(text).map_err(DrawingErrorKind::FontError)?; - let x0 = match style.anchor().h_pos { + let x0 = match anchor.h_pos { HPos::Left => x0, HPos::Center => x0 - fx1 / 2 + fx0 / 2, HPos::Right => x0 - fx1 + fx0, }; - let y0 = match style.anchor().v_pos { + let y0 = match anchor.v_pos { VPos::Top => y0, VPos::Center => y0 - fy1 / 2 + fy0 / 2, VPos::Bottom => y0 - fy1 + fy0, diff --git a/plotters/Cargo.toml b/plotters/Cargo.toml index 91f9025d..31b4e60b 100644 --- a/plotters/Cargo.toml +++ b/plotters/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "plotters" -version = "0.3.4" +version = "0.3.5" authors = ["Hao Hou "] edition = "2018" license = "MIT" @@ -9,7 +9,7 @@ repository = "https://github.com/plotters-rs/plotters" homepage = "https://plotters-rs.github.io/" keywords = ["WebAssembly", "Visualization", "Plotting", "Drawing"] categories = ["visualization", "wasm"] -readme = "README.md" +readme = "../README.md" exclude = ["doc-template", "plotters-doc-data"] [dependencies] @@ -17,23 +17,28 @@ num-traits = "0.2.14" chrono = { version = "0.4.20", optional = true } [dependencies.plotters-backend] +version = "0.3.5" path = "../plotters-backend" [dependencies.plotters-bitmap] +version = "0.3.3" default_features = false optional = true path = "../plotters-bitmap" [dependencies.plotters-svg] -version = "^0.3" +version = "0.3.5" optional = true path = "../plotters-svg" [target.'cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))'.dependencies] -ttf-parser = { version = "0.15.0", optional = true } +ttf-parser = { version = "0.17.0", optional = true } lazy_static = { version = "1.4.0", optional = true } pathfinder_geometry = { version = "0.5.1", optional = true } font-kit = { version = "0.11.0", optional = true } +ab_glyph = { version = "0.2.12", optional = true } +once_cell = { version = "1.8.0", optional = true } + [target.'cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))'.dependencies.image] version = "0.24.3" @@ -65,19 +70,21 @@ default = [ "ttf", "image", "deprecated_items", "all_series", "all_elements", - "full_palette" + "full_palette", + "colormaps" ] all_series = ["area_series", "line_series", "point_series", "surface_series"] all_elements = ["errorbar", "candlestick", "boxplot", "histogram"] # Tier 1 Backends -bitmap_backend = ["plotters-bitmap", "ttf"] +bitmap_backend = ["plotters-bitmap"] bitmap_encoder = ["plotters-bitmap/image_encoder"] bitmap_gif = ["plotters-bitmap/gif_backend"] svg_backend = ["plotters-svg"] # Colors full_palette = [] +colormaps = [] # Elements errorbar = [] @@ -97,6 +104,8 @@ ttf = ["font-kit", "ttf-parser", "lazy_static", "pathfinder_geometry"] # Can be useful for cross compiling, especially considering fontconfig has lots of C dependencies fontconfig-dlopen = ["font-kit/source-fontconfig-dlopen"] +ab_glyph = ["dep:ab_glyph", "once_cell"] + # Misc datetime = ["chrono"] evcxr = ["svg_backend"] @@ -105,7 +114,7 @@ deprecated_items = [] # Keep some of the deprecated items for backward compatibi [dev-dependencies] itertools = "0.10.0" -criterion = "0.3.6" +criterion = "0.4.0" rayon = "1.5.1" serde_json = "1.0.82" serde = "1.0.139" @@ -123,3 +132,8 @@ wasm-bindgen-test = "0.3.24" name = "benchmark" harness = false path = "benches/main.rs" + +[package.metadata.docs.rs] +all-features = true +rustdoc-args = ["--cfg", "doc_cfg"] + diff --git a/plotters/LICENSE b/plotters/LICENSE new file mode 120000 index 00000000..ea5b6064 --- /dev/null +++ b/plotters/LICENSE @@ -0,0 +1 @@ +../LICENSE \ No newline at end of file diff --git a/plotters/blub.png b/plotters/blub.png new file mode 100644 index 00000000..f65ee435 --- /dev/null +++ b/plotters/blub.png @@ -0,0 +1,3 @@ + + + diff --git a/plotters/examples/3d-plot.rs b/plotters/examples/3d-plot.rs index af40cc29..a5b3d068 100644 --- a/plotters/examples/3d-plot.rs +++ b/plotters/examples/3d-plot.rs @@ -1,5 +1,5 @@ use plotters::prelude::*; -const OUT_FILE_NAME: &'static str = "plotters-doc-data/3d-plot.svg"; +const OUT_FILE_NAME: &str = "plotters-doc-data/3d-plot.svg"; fn main() -> Result<(), Box> { let area = SVGBackend::new(OUT_FILE_NAME, (1024, 760)).into_drawing_area(); @@ -9,7 +9,7 @@ fn main() -> Result<(), Box> { let z_axis = (-3.0..3.0).step(0.1); let mut chart = ChartBuilder::on(&area) - .caption(format!("3D Plot Test"), ("sans", 20)) + .caption("3D Plot Test".to_string(), ("sans", 20)) .build_cartesian_3d(x_axis.clone(), -3.0..3.0, z_axis.clone())?; chart.with_projection(|mut pb| { @@ -44,12 +44,9 @@ fn main() -> Result<(), Box> { &BLACK, ))? .label("Line") - .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], &BLACK)); + .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], BLACK)); - chart - .configure_series_labels() - .border_style(&BLACK) - .draw()?; + chart.configure_series_labels().border_style(BLACK).draw()?; // To avoid the IO failure being ignored silently, we manually call the present function area.present().expect("Unable to write result to file, please make sure 'plotters-doc-data' dir exists under current dir"); diff --git a/plotters/examples/3d-plot2.rs b/plotters/examples/3d-plot2.rs index 0b5ca213..d8feeb9e 100644 --- a/plotters/examples/3d-plot2.rs +++ b/plotters/examples/3d-plot2.rs @@ -3,12 +3,12 @@ fn pdf(x: f64, y: f64) -> f64 { const SDX: f64 = 0.1; const SDY: f64 = 0.1; const A: f64 = 5.0; - let x = x as f64 / 10.0; - let y = y as f64 / 10.0; + let x = x / 10.0; + let y = y / 10.0; A * (-x * x / 2.0 / SDX / SDX - y * y / 2.0 / SDY / SDY).exp() } -const OUT_FILE_NAME: &'static str = "plotters-doc-data/3d-plot2.gif"; +const OUT_FILE_NAME: &str = "plotters-doc-data/3d-plot2.gif"; fn main() -> Result<(), Box> { let root = BitMapBackend::gif(OUT_FILE_NAME, (600, 400), 100)?.into_drawing_area(); @@ -36,9 +36,7 @@ fn main() -> Result<(), Box> { (-15..=15).map(|x| x as f64 / 5.0), pdf, ) - .style_func(&|&v| { - (&HSLColor(240.0 / 360.0 - 240.0 / 360.0 * v / 5.0, 1.0, 0.7)).into() - }), + .style_func(&|&v| (VulcanoHSL::get_color(v / 5.0)).into()), )?; root.present()?; diff --git a/plotters/examples/animation.rs b/plotters/examples/animation.rs index dab7d451..b93cb81a 100644 --- a/plotters/examples/animation.rs +++ b/plotters/examples/animation.rs @@ -17,7 +17,7 @@ fn snowflake_iter(points: &[(f64, f64)]) -> Vec<(f64, f64)> { ret } -const OUT_FILE_NAME: &'static str = "plotters-doc-data/animation.gif"; +const OUT_FILE_NAME: &str = "plotters-doc-data/animation.gif"; fn main() -> Result<(), Box> { let root = BitMapBackend::gif(OUT_FILE_NAME, (800, 600), 1_000)?.into_drawing_area(); @@ -45,11 +45,11 @@ fn main() -> Result<(), Box> { chart.draw_series(std::iter::once(Polygon::new( snowflake_vertices.clone(), - &RED.mix(0.2), + RED.mix(0.2), )))?; snowflake_vertices.push(snowflake_vertices[0]); - chart.draw_series(std::iter::once(PathElement::new(snowflake_vertices, &RED)))?; + chart.draw_series(std::iter::once(PathElement::new(snowflake_vertices, RED)))?; root.present()?; } diff --git a/plotters/examples/area-chart.rs b/plotters/examples/area-chart.rs index 5b1a7a5a..c6d78df2 100644 --- a/plotters/examples/area-chart.rs +++ b/plotters/examples/area-chart.rs @@ -4,7 +4,7 @@ use rand::SeedableRng; use rand_distr::{Distribution, Normal}; use rand_xorshift::XorShiftRng; -const OUT_FILE_NAME: &'static str = "plotters-doc-data/area-chart.png"; +const OUT_FILE_NAME: &str = "plotters-doc-data/area-chart.png"; fn main() -> Result<(), Box> { let data: Vec<_> = { let norm_dist = Normal::new(500.0, 100.0).unwrap(); @@ -38,9 +38,9 @@ fn main() -> Result<(), Box> { AreaSeries::new( (0..).zip(data.iter()).map(|(x, y)| (x, *y)), 0.0, - &RED.mix(0.2), + RED.mix(0.2), ) - .border_style(&RED), + .border_style(RED), )?; // To avoid the IO failure being ignored silently, we manually call the present function diff --git a/plotters/examples/blit-bitmap.rs b/plotters/examples/blit-bitmap.rs index 990b2564..bcdcd177 100644 --- a/plotters/examples/blit-bitmap.rs +++ b/plotters/examples/blit-bitmap.rs @@ -5,7 +5,7 @@ use image::{imageops::FilterType, ImageFormat}; use std::fs::File; use std::io::BufReader; -const OUT_FILE_NAME: &'static str = "plotters-doc-data/blit-bitmap.png"; +const OUT_FILE_NAME: &str = "plotters-doc-data/blit-bitmap.png"; fn main() -> Result<(), Box> { let root = BitMapBackend::new(OUT_FILE_NAME, (1024, 768)).into_drawing_area(); diff --git a/plotters/examples/boxplot.rs b/plotters/examples/boxplot.rs index 6e46db40..7acda7ab 100644 --- a/plotters/examples/boxplot.rs +++ b/plotters/examples/boxplot.rs @@ -21,7 +21,7 @@ fn read_data(reader: BR) -> HashMap<(String, String), Vec> { ds } -const OUT_FILE_NAME: &'static str = "plotters-doc-data/boxplot.svg"; +const OUT_FILE_NAME: &str = "plotters-doc-data/boxplot.svg"; fn main() -> Result<(), Box> { let root = SVGBackend::new(OUT_FILE_NAME, (1024, 768)).into_drawing_area(); root.fill(&WHITE)?; @@ -40,7 +40,7 @@ fn main() -> Result<(), Box> { }; let dataset: Vec<(String, String, Quartiles)> = ds .iter() - .map(|(k, v)| (k.0.clone(), k.1.clone(), Quartiles::new(&v))) + .map(|(k, v)| (k.0.clone(), k.1.clone(), Quartiles::new(v))) .collect(); let host_list: Vec<_> = dataset @@ -60,11 +60,7 @@ fn main() -> Result<(), Box> { entry.0.push((x.0.clone(), &x.2)); } - let values: Vec = dataset - .iter() - .map(|x| x.2.values().to_vec()) - .flatten() - .collect(); + let values: Vec = dataset.iter().flat_map(|x| x.2.values().to_vec()).collect(); let values_range = fitting_range(values.iter()); let mut chart = ChartBuilder::on(&upper) @@ -81,13 +77,13 @@ fn main() -> Result<(), Box> { .x_desc("Ping, ms") .y_desc("Host") .y_labels(host_list.len()) - .light_line_style(&WHITE) + .light_line_style(WHITE) .draw()?; for (label, (values, style, offset)) in &series { chart .draw_series(values.iter().map(|x| { - Boxplot::new_horizontal(SegmentValue::CenterOf(&x.0), &x.1) + Boxplot::new_horizontal(SegmentValue::CenterOf(&x.0), x.1) .width(20) .whisker_width(0.5) .style(style) @@ -100,7 +96,7 @@ fn main() -> Result<(), Box> { .configure_series_labels() .position(SeriesLabelPosition::UpperRight) .background_style(WHITE.filled()) - .border_style(&BLACK.mix(0.5)) + .border_style(BLACK.mix(0.5)) .legend_area_size(22) .draw()?; @@ -120,7 +116,7 @@ fn main() -> Result<(), Box> { .iter() .chain(quartiles_b.values().iter()), ); - let mut chart = ChartBuilder::on(&left) + let mut chart = ChartBuilder::on(left) .x_label_area_size(40) .y_label_area_size(40) .caption("Vertical Boxplot", ("sans-serif", 20)) @@ -129,19 +125,19 @@ fn main() -> Result<(), Box> { values_range.start - 10.0..values_range.end + 10.0, )?; - chart.configure_mesh().light_line_style(&WHITE).draw()?; + chart.configure_mesh().light_line_style(WHITE).draw()?; chart.draw_series(vec![ Boxplot::new_vertical(SegmentValue::CenterOf(&"a"), &quartiles_a), Boxplot::new_vertical(SegmentValue::CenterOf(&"b"), &quartiles_b), ])?; - let mut chart = ChartBuilder::on(&right) + let mut chart = ChartBuilder::on(right) .x_label_area_size(40) .y_label_area_size(40) .caption("Horizontal Boxplot", ("sans-serif", 20)) .build_cartesian_2d(-30f32..90f32, 0..3)?; - chart.configure_mesh().light_line_style(&WHITE).draw()?; + chart.configure_mesh().light_line_style(WHITE).draw()?; chart.draw_series(vec![ Boxplot::new_horizontal(1, &quartiles_a), Boxplot::new_horizontal(2, &Quartiles::new(&[30])), diff --git a/plotters/examples/chart.rs b/plotters/examples/chart.rs index acdddc3c..e121041e 100644 --- a/plotters/examples/chart.rs +++ b/plotters/examples/chart.rs @@ -1,6 +1,6 @@ use plotters::prelude::*; -const OUT_FILE_NAME: &'static str = "plotters-doc-data/sample.png"; +const OUT_FILE_NAME: &str = "plotters-doc-data/sample.png"; fn main() -> Result<(), Box> { let root_area = BitMapBackend::new(OUT_FILE_NAME, (1024, 768)).into_drawing_area(); @@ -28,16 +28,16 @@ fn main() -> Result<(), Box> { cc.draw_series(LineSeries::new(x_axis.values().map(|x| (x, x.sin())), &RED))? .label("Sine") - .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], &RED)); + .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], RED)); cc.draw_series(LineSeries::new( x_axis.values().map(|x| (x, x.cos())), &BLUE, ))? .label("Cosine") - .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], &BLUE)); + .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], BLUE)); - cc.configure_series_labels().border_style(&BLACK).draw()?; + cc.configure_series_labels().border_style(BLACK).draw()?; /* // It's possible to use a existing pointing element @@ -62,7 +62,7 @@ fn main() -> Result<(), Box> { let drawing_areas = lower.split_evenly((1, 2)); for (drawing_area, idx) in drawing_areas.iter().zip(1..) { - let mut cc = ChartBuilder::on(&drawing_area) + let mut cc = ChartBuilder::on(drawing_area) .x_label_area_size(30) .y_label_area_size(30) .margin_right(20) diff --git a/plotters/examples/colormaps.rs b/plotters/examples/colormaps.rs new file mode 100644 index 00000000..3749e43d --- /dev/null +++ b/plotters/examples/colormaps.rs @@ -0,0 +1,69 @@ +use plotters::prelude::*; + +const OUT_FILE_NAME: &str = "plotters-doc-data/colormaps.png"; + +fn main() -> Result<(), Box> { + let colormaps_rgb: [(Box>, &str); 4] = [ + (Box::new(ViridisRGB {}), "Viridis"), + (Box::new(BlackWhite {}), "BlackWhite"), + (Box::new(Bone {}), "Bone"), + (Box::new(Copper {}), "Copper"), + ]; + + let colormaps_hsl: [(Box>, &str); 2] = [ + (Box::new(MandelbrotHSL {}), "MandelbrotHSL"), + (Box::new(VulcanoHSL {}), "VulcanoHSL"), + ]; + + let size_x: i32 = 800; + let n_colormaps = colormaps_rgb.len() + colormaps_hsl.len(); + let size_y = 200 + n_colormaps as u32 * 100; + let root = BitMapBackend::new(OUT_FILE_NAME, (size_x as u32, size_y)).into_drawing_area(); + + root.fill(&WHITE)?; + + let mut chart = ChartBuilder::on(&root) + .caption("Demonstration of predefined colormaps", ("sans-serif", 20)) + .build_cartesian_2d( + -150.0..size_x as f32 + 50.0, + 0.0..3.0 * (n_colormaps as f32), + )?; + + use plotters::style::text_anchor::*; + let centered = Pos::new(HPos::Center, VPos::Center); + let label_style = TextStyle::from(("monospace", 14.0).into_font()).pos(centered); + + let mut colormap_counter = 0; + macro_rules! plot_colormaps( + ($colormap:expr) => { + for (colormap, colormap_name) in $colormap.iter() { + chart.draw_series( + (0..size_x as i32).map(|x| { + Rectangle::new([ + (x as f32, 3.0*(n_colormaps - 1 - colormap_counter) as f32 + 0.5), + (x as f32+1.0, 3.0*(n_colormaps - 1 - colormap_counter) as f32 + 2.5) + ], + colormap.get_color_normalized(x as f32, 0.0, size_x as f32).filled()) + }) + )?; + chart.draw_series( + [Text::new(colormap_name.to_owned(), (-75.0, 3.0*(n_colormaps-1-colormap_counter) as f32 + 1.5), &label_style)] + )?; + colormap_counter+=1; + } + } + ); + + plot_colormaps!(colormaps_rgb); + plot_colormaps!(colormaps_hsl); + + // To avoid the IO failure being ignored silently, we manually call the present function + root.present().expect("Unable to write result to file, please make sure 'plotters-doc-data' dir exists under current dir"); + println!("Result has been saved to {}", OUT_FILE_NAME); + + Ok(()) +} +#[test] +fn entry_point() { + main().unwrap() +} diff --git a/plotters/examples/console.rs b/plotters/examples/console.rs index feba0956..845e9e60 100644 --- a/plotters/examples/console.rs +++ b/plotters/examples/console.rs @@ -131,12 +131,13 @@ impl DrawingBackend for TextDrawingBackend { ) -> Result<(), DrawingErrorKind> { let (width, height) = self.estimate_text_size(text, style)?; let (width, height) = (width as i32, height as i32); - let dx = match style.anchor().h_pos { + let style = style.anchor().unwrap_or_default(); + let dx = match style.h_pos { HPos::Left => 0, HPos::Right => -width, HPos::Center => -width / 2, }; - let dy = match style.anchor().v_pos { + let dy = match style.v_pos { VPos::Top => 0, VPos::Center => -height / 2, VPos::Bottom => -height, @@ -183,7 +184,7 @@ where Ok(()) } -const OUT_FILE_NAME: &'static str = "plotters-doc-data/console-example.png"; +const OUT_FILE_NAME: &str = "plotters-doc-data/console-example.png"; fn main() -> Result<(), Box> { draw_chart(TextDrawingBackend(vec![PixelState::Empty; 5000]).into_drawing_area())?; let b = BitMapBackend::new(OUT_FILE_NAME, (1024, 768)).into_drawing_area(); diff --git a/plotters/examples/customized_coord.rs b/plotters/examples/customized_coord.rs index cb3a18f0..760373bc 100644 --- a/plotters/examples/customized_coord.rs +++ b/plotters/examples/customized_coord.rs @@ -2,7 +2,7 @@ use plotters::{ coord::ranged1d::{KeyPointHint, NoDefaultFormatting, ValueFormatter}, prelude::*, }; -const OUT_FILE_NAME: &'static str = "plotters-doc-data/customized_coord.svg"; +const OUT_FILE_NAME: &str = "plotters-doc-data/customized_coord.svg"; struct CustomizedX(u32); diff --git a/plotters/examples/errorbar.rs b/plotters/examples/errorbar.rs index 75c5dbea..364ea899 100644 --- a/plotters/examples/errorbar.rs +++ b/plotters/examples/errorbar.rs @@ -8,7 +8,7 @@ use itertools::Itertools; use num_traits::sign::Signed; -const OUT_FILE_NAME: &'static str = "plotters-doc-data/errorbar.png"; +const OUT_FILE_NAME: &str = "plotters-doc-data/errorbar.png"; fn main() -> Result<(), Box> { let data = generate_random_data(); let down_sampled = down_sample(&data[..]); @@ -29,7 +29,7 @@ fn main() -> Result<(), Box> { chart .draw_series(LineSeries::new(data, &GREEN.mix(0.3)))? .label("Raw Data") - .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], &GREEN)); + .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], GREEN)); chart.draw_series(LineSeries::new( down_sampled.iter().map(|(x, _, y, _)| (*x, *y)), @@ -43,7 +43,7 @@ fn main() -> Result<(), Box> { }), )? .label("Down-sampled") - .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], &BLUE)); + .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], BLUE)); chart .configure_series_labels() diff --git a/plotters/examples/full_palette.rs b/plotters/examples/full_palette.rs index dbd0d429..b63ea73e 100644 --- a/plotters/examples/full_palette.rs +++ b/plotters/examples/full_palette.rs @@ -1,6 +1,6 @@ use plotters::prelude::*; -const OUT_FILE_NAME: &'static str = "plotters-doc-data/full_palette.png"; +const OUT_FILE_NAME: &str = "plotters-doc-data/full_palette.png"; fn main() -> Result<(), Box> { let root = BitMapBackend::new(OUT_FILE_NAME, (2000, 850)).into_drawing_area(); diff --git a/plotters/examples/histogram.rs b/plotters/examples/histogram.rs index 5cda05db..a56ce026 100644 --- a/plotters/examples/histogram.rs +++ b/plotters/examples/histogram.rs @@ -1,5 +1,5 @@ use plotters::prelude::*; -const OUT_FILE_NAME: &'static str = "plotters-doc-data/histogram.png"; +const OUT_FILE_NAME: &str = "plotters-doc-data/histogram.png"; fn main() -> Result<(), Box> { let root = BitMapBackend::new(OUT_FILE_NAME, (640, 480)).into_drawing_area(); @@ -15,7 +15,7 @@ fn main() -> Result<(), Box> { chart .configure_mesh() .disable_x_mesh() - .bold_line_style(&WHITE.mix(0.3)) + .bold_line_style(WHITE.mix(0.3)) .y_desc("Count") .x_desc("Bucket") .axis_desc_style(("sans-serif", 15)) diff --git a/plotters/examples/mandelbrot.rs b/plotters/examples/mandelbrot.rs index 413c319c..a03ae1c5 100644 --- a/plotters/examples/mandelbrot.rs +++ b/plotters/examples/mandelbrot.rs @@ -1,7 +1,7 @@ use plotters::prelude::*; use std::ops::Range; -const OUT_FILE_NAME: &'static str = "plotters-doc-data/mandelbrot.png"; +const OUT_FILE_NAME: &str = "plotters-doc-data/mandelbrot.png"; fn main() -> Result<(), Box> { let root = BitMapBackend::new(OUT_FILE_NAME, (800, 600)).into_drawing_area(); @@ -28,7 +28,7 @@ fn main() -> Result<(), Box> { for (x, y, c) in mandelbrot_set(xr, yr, (pw as usize, ph as usize), 100) { if c != 100 { - plotting_area.draw_pixel((x, y), &HSLColor(c as f64 / 100.0, 1.0, 0.5))?; + plotting_area.draw_pixel((x, y), &MandelbrotHSL::get_color(c as f64 / 100.0))?; } else { plotting_area.draw_pixel((x, y), &BLACK)?; } @@ -51,7 +51,7 @@ fn mandelbrot_set( (real.end - real.start) / samples.0 as f64, (complex.end - complex.start) / samples.1 as f64, ); - return (0..(samples.0 * samples.1)).map(move |k| { + (0..(samples.0 * samples.1)).map(move |k| { let c = ( real.start + step.0 * (k % samples.0) as f64, complex.start + step.1 * (k / samples.0) as f64, @@ -62,8 +62,8 @@ fn mandelbrot_set( z = (z.0 * z.0 - z.1 * z.1 + c.0, 2.0 * z.0 * z.1 + c.1); cnt += 1; } - return (c.0, c.1, cnt); - }); + (c.0, c.1, cnt) + }) } #[test] fn entry_point() { diff --git a/plotters/examples/matshow.rs b/plotters/examples/matshow.rs index 30c71a74..967af360 100644 --- a/plotters/examples/matshow.rs +++ b/plotters/examples/matshow.rs @@ -1,6 +1,6 @@ use plotters::prelude::*; -const OUT_FILE_NAME: &'static str = "plotters-doc-data/matshow.png"; +const OUT_FILE_NAME: &str = "plotters-doc-data/matshow.png"; fn main() -> Result<(), Box> { let root = BitMapBackend::new(OUT_FILE_NAME, (1024, 768)).into_drawing_area(); @@ -35,8 +35,7 @@ fn main() -> Result<(), Box> { matrix .iter() .zip(0..) - .map(|(l, y)| l.iter().zip(0..).map(move |(v, x)| (x as i32, y as i32, v))) - .flatten() + .flat_map(|(l, y)| l.iter().zip(0..).map(move |(v, x)| (x, y, v))) .map(|(x, y, v)| { Rectangle::new( [(x, y), (x + 1, y + 1)], diff --git a/plotters/examples/nested_coord.rs b/plotters/examples/nested_coord.rs index b7001014..a3418fa9 100644 --- a/plotters/examples/nested_coord.rs +++ b/plotters/examples/nested_coord.rs @@ -1,5 +1,5 @@ use plotters::prelude::*; -const OUT_FILE_NAME: &'static str = "plotters-doc-data/nested_coord.png"; +const OUT_FILE_NAME: &str = "plotters-doc-data/nested_coord.png"; fn main() -> Result<(), Box> { let root = BitMapBackend::new(OUT_FILE_NAME, (640, 480)).into_drawing_area(); diff --git a/plotters/examples/normal-dist.rs b/plotters/examples/normal-dist.rs index be487863..e6cfdcd6 100644 --- a/plotters/examples/normal-dist.rs +++ b/plotters/examples/normal-dist.rs @@ -4,7 +4,7 @@ use rand::SeedableRng; use rand_distr::{Distribution, Normal}; use rand_xorshift::XorShiftRng; -const OUT_FILE_NAME: &'static str = "plotters-doc-data/normal-dist.png"; +const OUT_FILE_NAME: &str = "plotters-doc-data/normal-dist.png"; fn main() -> Result<(), Box> { let root = BitMapBackend::new(OUT_FILE_NAME, (1024, 768)).into_drawing_area(); diff --git a/plotters/examples/normal-dist2.rs b/plotters/examples/normal-dist2.rs index 6c84ab3a..f9963123 100644 --- a/plotters/examples/normal-dist2.rs +++ b/plotters/examples/normal-dist2.rs @@ -6,7 +6,7 @@ use rand_xorshift::XorShiftRng; use num_traits::sign::Signed; -const OUT_FILE_NAME: &'static str = "plotters-doc-data/normal-dist2.png"; +const OUT_FILE_NAME: &str = "plotters-doc-data/normal-dist2.png"; fn main() -> Result<(), Box> { let sd = 0.60; diff --git a/plotters/examples/pie.rs b/plotters/examples/pie.rs index a950c021..7226e5a3 100644 --- a/plotters/examples/pie.rs +++ b/plotters/examples/pie.rs @@ -1,6 +1,6 @@ use plotters::{prelude::*, style::full_palette::ORANGE}; -const OUT_FILE_NAME: &'static str = "plotters-doc-data/pie-chart.png"; +const OUT_FILE_NAME: &str = "plotters-doc-data/pie-chart.png"; fn main() -> Result<(), Box> { let root_area = BitMapBackend::new(&OUT_FILE_NAME, (950, 700)).into_drawing_area(); root_area.fill(&WHITE).unwrap(); diff --git a/plotters/examples/relative_size.rs b/plotters/examples/relative_size.rs index 66eaec13..e66bfeef 100644 --- a/plotters/examples/relative_size.rs +++ b/plotters/examples/relative_size.rs @@ -28,7 +28,7 @@ fn draw_chart(root: &DrawingArea) -> DrawResult<(), Ok(()) } -const OUT_FILE_NAME: &'static str = "plotters-doc-data/relative_size.png"; +const OUT_FILE_NAME: &str = "plotters-doc-data/relative_size.png"; fn main() -> Result<(), Box> { let root = BitMapBackend::new(OUT_FILE_NAME, (1024, 768)).into_drawing_area(); diff --git a/plotters/examples/sierpinski.rs b/plotters/examples/sierpinski.rs index b9655bf9..773d1b2c 100644 --- a/plotters/examples/sierpinski.rs +++ b/plotters/examples/sierpinski.rs @@ -19,7 +19,7 @@ pub fn sierpinski_carpet( Ok(()) } -const OUT_FILE_NAME: &'static str = "plotters-doc-data/sierpinski.png"; +const OUT_FILE_NAME: &str = "plotters-doc-data/sierpinski.png"; fn main() -> Result<(), Box> { let root = BitMapBackend::new(OUT_FILE_NAME, (1024, 768)).into_drawing_area(); diff --git a/plotters/examples/slc-temp.rs b/plotters/examples/slc-temp.rs index 9d6e4731..a774995d 100644 --- a/plotters/examples/slc-temp.rs +++ b/plotters/examples/slc-temp.rs @@ -4,7 +4,7 @@ use chrono::{TimeZone, Utc}; use std::error::Error; -const OUT_FILE_NAME: &'static str = "plotters-doc-data/slc-temp.png"; +const OUT_FILE_NAME: &str = "plotters-doc-data/slc-temp.png"; fn main() -> Result<(), Box> { let root = BitMapBackend::new(OUT_FILE_NAME, (1024, 768)).into_drawing_area(); diff --git a/plotters/examples/snowflake.rs b/plotters/examples/snowflake.rs index 6e52f25b..f64a0d67 100644 --- a/plotters/examples/snowflake.rs +++ b/plotters/examples/snowflake.rs @@ -17,7 +17,7 @@ fn snowflake_iter(points: &[(f64, f64)]) -> Vec<(f64, f64)> { ret } -const OUT_FILE_NAME: &'static str = "plotters-doc-data/snowflake.png"; +const OUT_FILE_NAME: &str = "plotters-doc-data/snowflake.png"; fn main() -> Result<(), Box> { let root = BitMapBackend::new(OUT_FILE_NAME, (1024, 768)).into_drawing_area(); @@ -41,10 +41,10 @@ fn main() -> Result<(), Box> { chart.draw_series(std::iter::once(Polygon::new( snowflake_vertices.clone(), - &RED.mix(0.2), + RED.mix(0.2), )))?; snowflake_vertices.push(snowflake_vertices[0]); - chart.draw_series(std::iter::once(PathElement::new(snowflake_vertices, &RED)))?; + chart.draw_series(std::iter::once(PathElement::new(snowflake_vertices, RED)))?; // To avoid the IO failure being ignored silently, we manually call the present function root.present().expect("Unable to write result to file, please make sure 'plotters-doc-data' dir exists under current dir"); diff --git a/plotters/examples/stock.rs b/plotters/examples/stock.rs index 8e9416f6..65defad2 100644 --- a/plotters/examples/stock.rs +++ b/plotters/examples/stock.rs @@ -7,15 +7,15 @@ fn parse_time(t: &str) -> Date { .unwrap() .date() } -const OUT_FILE_NAME: &'static str = "plotters-doc-data/stock.png"; +const OUT_FILE_NAME: &str = "plotters-doc-data/stock.png"; fn main() -> Result<(), Box> { let data = get_data(); let root = BitMapBackend::new(OUT_FILE_NAME, (1024, 768)).into_drawing_area(); root.fill(&WHITE)?; let (to_date, from_date) = ( - parse_time(&data[0].0) + Duration::days(1), - parse_time(&data[29].0) - Duration::days(1), + parse_time(data[0].0) + Duration::days(1), + parse_time(data[29].0) - Duration::days(1), ); let mut chart = ChartBuilder::on(&root) @@ -24,7 +24,7 @@ fn main() -> Result<(), Box> { .caption("MSFT Stock Price", ("sans-serif", 50.0).into_font()) .build_cartesian_2d(from_date..to_date, 110f32..135f32)?; - chart.configure_mesh().light_line_style(&WHITE).draw()?; + chart.configure_mesh().light_line_style(WHITE).draw()?; chart.draw_series( data.iter().map(|x| { @@ -40,38 +40,38 @@ fn main() -> Result<(), Box> { } fn get_data() -> Vec<(&'static str, f32, f32, f32, f32)> { - return vec![ - ("2019-04-25", 130.0600, 131.3700, 128.8300, 129.1500), - ("2019-04-24", 125.7900, 125.8500, 124.5200, 125.0100), - ("2019-04-23", 124.1000, 125.5800, 123.8300, 125.4400), - ("2019-04-22", 122.6200, 124.0000, 122.5700, 123.7600), - ("2019-04-18", 122.1900, 123.5200, 121.3018, 123.3700), - ("2019-04-17", 121.2400, 121.8500, 120.5400, 121.7700), - ("2019-04-16", 121.6400, 121.6500, 120.1000, 120.7700), - ("2019-04-15", 120.9400, 121.5800, 120.5700, 121.0500), - ("2019-04-12", 120.6400, 120.9800, 120.3700, 120.9500), - ("2019-04-11", 120.5400, 120.8500, 119.9200, 120.3300), - ("2019-04-10", 119.7600, 120.3500, 119.5400, 120.1900), - ("2019-04-09", 118.6300, 119.5400, 118.5800, 119.2800), - ("2019-04-08", 119.8100, 120.0200, 118.6400, 119.9300), - ("2019-04-05", 119.3900, 120.2300, 119.3700, 119.8900), - ("2019-04-04", 120.1000, 120.2300, 118.3800, 119.3600), - ("2019-04-03", 119.8600, 120.4300, 119.1500, 119.9700), - ("2019-04-02", 119.0600, 119.4800, 118.5200, 119.1900), - ("2019-04-01", 118.9500, 119.1085, 118.1000, 119.0200), - ("2019-03-29", 118.0700, 118.3200, 116.9600, 117.9400), - ("2019-03-28", 117.4400, 117.5800, 116.1300, 116.9300), - ("2019-03-27", 117.8750, 118.2100, 115.5215, 116.7700), - ("2019-03-26", 118.6200, 118.7050, 116.8500, 117.9100), - ("2019-03-25", 116.5600, 118.0100, 116.3224, 117.6600), - ("2019-03-22", 119.5000, 119.5900, 117.0400, 117.0500), - ("2019-03-21", 117.1350, 120.8200, 117.0900, 120.2200), - ("2019-03-20", 117.3900, 118.7500, 116.7100, 117.5200), - ("2019-03-19", 118.0900, 118.4400, 116.9900, 117.6500), - ("2019-03-18", 116.1700, 117.6100, 116.0500, 117.5700), - ("2019-03-15", 115.3400, 117.2500, 114.5900, 115.9100), - ("2019-03-14", 114.5400, 115.2000, 114.3300, 114.5900), - ]; + vec![ + ("2019-04-25", 130.06, 131.37, 128.83, 129.15), + ("2019-04-24", 125.79, 125.85, 124.52, 125.01), + ("2019-04-23", 124.1, 125.58, 123.83, 125.44), + ("2019-04-22", 122.62, 124.0000, 122.57, 123.76), + ("2019-04-18", 122.19, 123.52, 121.3018, 123.37), + ("2019-04-17", 121.24, 121.85, 120.54, 121.77), + ("2019-04-16", 121.64, 121.65, 120.1, 120.77), + ("2019-04-15", 120.94, 121.58, 120.57, 121.05), + ("2019-04-12", 120.64, 120.98, 120.37, 120.95), + ("2019-04-11", 120.54, 120.85, 119.92, 120.33), + ("2019-04-10", 119.76, 120.35, 119.54, 120.19), + ("2019-04-09", 118.63, 119.54, 118.58, 119.28), + ("2019-04-08", 119.81, 120.02, 118.64, 119.93), + ("2019-04-05", 119.39, 120.23, 119.37, 119.89), + ("2019-04-04", 120.1, 120.23, 118.38, 119.36), + ("2019-04-03", 119.86, 120.43, 119.15, 119.97), + ("2019-04-02", 119.06, 119.48, 118.52, 119.19), + ("2019-04-01", 118.95, 119.1085, 118.1, 119.02), + ("2019-03-29", 118.07, 118.32, 116.96, 117.94), + ("2019-03-28", 117.44, 117.58, 116.13, 116.93), + ("2019-03-27", 117.875, 118.21, 115.5215, 116.77), + ("2019-03-26", 118.62, 118.705, 116.85, 117.91), + ("2019-03-25", 116.56, 118.01, 116.3224, 117.66), + ("2019-03-22", 119.5, 119.59, 117.04, 117.05), + ("2019-03-21", 117.135, 120.82, 117.09, 120.22), + ("2019-03-20", 117.39, 118.75, 116.71, 117.52), + ("2019-03-19", 118.09, 118.44, 116.99, 117.65), + ("2019-03-18", 116.17, 117.61, 116.05, 117.57), + ("2019-03-15", 115.34, 117.25, 114.59, 115.91), + ("2019-03-14", 114.54, 115.2, 114.33, 114.59), + ] } #[test] fn entry_point() { diff --git a/plotters/examples/tick_control.rs b/plotters/examples/tick_control.rs index b34fc88c..2f4ea348 100644 --- a/plotters/examples/tick_control.rs +++ b/plotters/examples/tick_control.rs @@ -16,7 +16,7 @@ struct CountryData { data: Vec, } -const OUT_FILE_NAME: &'static str = "plotters-doc-data/tick_control.svg"; +const OUT_FILE_NAME: &str = "plotters-doc-data/tick_control.svg"; fn main() -> Result<(), Box> { let root = SVGBackend::new(OUT_FILE_NAME, (1024, 768)).into_drawing_area(); root.fill(&WHITE)?; @@ -72,10 +72,7 @@ fn main() -> Result<(), Box> { .legend(move |(x, y)| Rectangle::new([(x, y - 5), (x + 10, y + 5)], color.filled())); } - chart - .configure_series_labels() - .border_style(&BLACK) - .draw()?; + chart.configure_series_labels().border_style(BLACK).draw()?; // To avoid the IO failure being ignored silently, we manually call the present function root.present().expect("Unable to write result to file, please make sure 'plotters-doc-data' dir exists under current dir"); diff --git a/plotters/examples/two-scales.rs b/plotters/examples/two-scales.rs index 6e1dfa4c..e50410fb 100644 --- a/plotters/examples/two-scales.rs +++ b/plotters/examples/two-scales.rs @@ -1,6 +1,6 @@ use plotters::prelude::*; -const OUT_FILE_NAME: &'static str = "plotters-doc-data/twoscale.png"; +const OUT_FILE_NAME: &str = "plotters-doc-data/twoscale.png"; fn main() -> Result<(), Box> { let root = BitMapBackend::new(OUT_FILE_NAME, (1024, 768)).into_drawing_area(); root.fill(&WHITE)?; @@ -33,7 +33,7 @@ fn main() -> Result<(), Box> { &BLUE, ))? .label("y = 1.02^x^2") - .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], &BLUE)); + .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], BLUE)); chart .draw_secondary_series(LineSeries::new( @@ -41,11 +41,11 @@ fn main() -> Result<(), Box> { &RED, ))? .label("y = sin(2x)") - .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], &RED)); + .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], RED)); chart .configure_series_labels() - .background_style(&RGBColor(128, 128, 128)) + .background_style(RGBColor(128, 128, 128)) .draw()?; // To avoid the IO failure being ignored silently, we manually call the present function diff --git a/plotters/src/chart/axes3d.rs b/plotters/src/chart/axes3d.rs index 33d7de39..9431715e 100644 --- a/plotters/src/chart/axes3d.rs +++ b/plotters/src/chart/axes3d.rs @@ -221,10 +221,10 @@ where tick_size, light_lines_limit: [10, 10, 10], n_labels: [10, 10, 10], - bold_line_style: Into::::into(&BLACK.mix(0.2)), - light_line_style: Into::::into(&TRANSPARENT), - axis_panel_style: Into::::into(&BLACK.mix(0.1)), - axis_style: Into::::into(&BLACK.mix(0.8)), + bold_line_style: Into::::into(BLACK.mix(0.2)), + light_line_style: Into::::into(TRANSPARENT), + axis_panel_style: Into::::into(BLACK.mix(0.1)), + axis_style: Into::::into(BLACK.mix(0.8)), label_style: ("sans-serif", (12).percent().max(12).in_pixels(&parent_size)).into(), format_x: &X::format, format_y: &Y::format, diff --git a/plotters/src/chart/context.rs b/plotters/src/chart/context.rs index ef91af19..c63ee3b0 100644 --- a/plotters/src/chart/context.rs +++ b/plotters/src/chart/context.rs @@ -171,13 +171,13 @@ mod test { let mut chart = cs.clone().restore(&drawing_area); chart - .draw_series(std::iter::once(Circle::new((5, 5), 5, &RED))) + .draw_series(std::iter::once(Circle::new((5, 5), 5, RED))) .expect("Drawing error"); chart - .draw_secondary_series(std::iter::once(Circle::new((0.3, 0.8), 5, &GREEN))) + .draw_secondary_series(std::iter::once(Circle::new((0.3, 0.8), 5, GREEN))) .expect("Drawing error") .label("Test label") - .legend(|(x, y)| Rectangle::new([(x - 10, y - 5), (x, y + 5)], &GREEN)); + .legend(|(x, y)| Rectangle::new([(x - 10, y - 5), (x, y + 5)], GREEN)); chart .configure_series_labels() @@ -215,7 +215,7 @@ mod test { let mut chart = cs.clone().restore(&drawing_area); chart - .draw_series(std::iter::once(Circle::new((5, 5, 5), 5, &RED))) + .draw_series(std::iter::once(Circle::new((5, 5, 5), 5, RED))) .expect("Drawing error"); } } diff --git a/plotters/src/chart/context/cartesian2d/draw_impl.rs b/plotters/src/chart/context/cartesian2d/draw_impl.rs index 6dafa087..e4f09bf1 100644 --- a/plotters/src/chart/context/cartesian2d/draw_impl.rs +++ b/plotters/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) @@ -250,8 +247,12 @@ impl<'a, DB: DrawingBackend, X: Ranged, Y: Ranged> ChartContext<'a, DB, Cartesia (cx, cy + label_offset) }; - let label_style = &label_style.pos(Pos::new(h_pos, v_pos)); - area.draw_text(t, label_style, (text_x, text_y))?; + let label_style_with_new_pos = label_style.pos(Pos::new(h_pos, v_pos)); + let label_style = match label_style.pos { + Some(_) => label_style, + None => &label_style_with_new_pos, + }; + area.draw_text(t, &label_style, (text_x, text_y))?; if tick_size != 0 { if let Some(style) = axis_style { diff --git a/plotters/src/chart/context/cartesian3d/draw_impl.rs b/plotters/src/chart/context/cartesian3d/draw_impl.rs index fcc4c4f7..7ef47f9b 100644 --- a/plotters/src/chart/context/cartesian3d/draw_impl.rs +++ b/plotters/src/chart/context/cartesian3d/draw_impl.rs @@ -95,16 +95,18 @@ where let logic_pos = Coord3D::build_coord([&pos[0], &pos[1], &pos[2]]); let mut font = font.clone(); - match dir.0.cmp(&0) { - Ordering::Less => font.pos = Pos::new(HPos::Right, VPos::Center), - Ordering::Greater => font.pos = Pos::new(HPos::Left, VPos::Center), - _ => (), - } + if font.pos.is_none() { + match dir.0.cmp(&0) { + Ordering::Less => font.pos = Some(Pos::new(HPos::Right, VPos::Center)), + Ordering::Greater => font.pos = Some(Pos::new(HPos::Left, VPos::Center)), + _ => (), + } - match dir.1.cmp(&0) { - Ordering::Less => font.pos = Pos::new(HPos::Center, VPos::Bottom), - Ordering::Greater => font.pos = Pos::new(HPos::Center, VPos::Top), - _ => (), + match dir.1.cmp(&0) { + Ordering::Less => font.pos = Some(Pos::new(HPos::Center, VPos::Bottom)), + Ordering::Greater => font.pos = Some(Pos::new(HPos::Center, VPos::Top)), + _ => (), + } } let element = EmptyElement::at(logic_pos) diff --git a/plotters/src/chart/dual_coord.rs b/plotters/src/chart/dual_coord.rs index d5960e03..434e3477 100644 --- a/plotters/src/chart/dual_coord.rs +++ b/plotters/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 /// 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/plotters/src/chart/series.rs b/plotters/src/chart/series.rs index 8c430cbe..3583f0fa 100644 --- a/plotters/src/chart/series.rs +++ b/plotters/src/chart/series.rs @@ -101,18 +101,14 @@ impl SeriesLabelPosition { ( match self { UpperLeft | MiddleLeft | LowerLeft => 5, - UpperMiddle | MiddleMiddle | LowerMiddle => { - (area_dim.0 as i32 - label_dim.0 as i32) / 2 - } - UpperRight | MiddleRight | LowerRight => area_dim.0 as i32 - label_dim.0 as i32 - 5, + UpperMiddle | MiddleMiddle | LowerMiddle => (area_dim.0 as i32 - label_dim.0) / 2, + UpperRight | MiddleRight | LowerRight => area_dim.0 as i32 - label_dim.0 - 5, Coordinate(x, _) => *x, }, match self { UpperLeft | UpperMiddle | UpperRight => 5, - MiddleLeft | MiddleMiddle | MiddleRight => { - (area_dim.1 as i32 - label_dim.1 as i32) / 2 - } - LowerLeft | LowerMiddle | LowerRight => area_dim.1 as i32 - label_dim.1 as i32 - 5, + MiddleLeft | MiddleMiddle | MiddleRight => (area_dim.1 as i32 - label_dim.1) / 2, + LowerLeft | LowerMiddle | LowerRight => area_dim.1 as i32 - label_dim.1 - 5, Coordinate(_, y) => *y, }, ) @@ -250,9 +246,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/plotters/src/coord/ranged1d/combinators/logarithmic.rs b/plotters/src/coord/ranged1d/combinators/logarithmic.rs index fee36f37..f105ff01 100644 --- a/plotters/src/coord/ranged1d/combinators/logarithmic.rs +++ b/plotters/src/coord/ranged1d/combinators/logarithmic.rs @@ -46,11 +46,14 @@ impl_log_scalable!(i, u8); impl_log_scalable!(i, u16); impl_log_scalable!(i, u32); impl_log_scalable!(i, u64); +impl_log_scalable!(i, usize); impl_log_scalable!(i, i8); impl_log_scalable!(i, i16); impl_log_scalable!(i, i32); impl_log_scalable!(i, i64); +impl_log_scalable!(i, i128); +impl_log_scalable!(i, isize); impl_log_scalable!(f, f32); impl_log_scalable!(f, f64); diff --git a/plotters/src/coord/ranged1d/types/datetime.rs b/plotters/src/coord/ranged1d/types/datetime.rs index 9b12358c..abd0a78b 100644 --- a/plotters/src/coord/ranged1d/types/datetime.rs +++ b/plotters/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 TimeValue for Date { fn subtract(&self, other: &Date) -> Duration { self.clone() - other.clone() } + fn add(&self, other: &Duration) -> Date { + 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 TimeValue for DateTime { fn subtract(&self, other: &DateTime) -> Duration { self.clone() - other.clone() } + fn add(&self, other: &Duration) -> DateTime { + 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
ReversibleRanged for RangedDateTime
+where + DT: Datelike + Timelike + TimeValue + Clone + PartialOrd, + DT: Add, + DT: Sub, + RangedDate: Ranged, +{ + /// Perform the reverse mapping + fn unmap(&self, input: i32, limit: (i32, i32)) -> Option { + Some(TimeValue::unmap_coord(input, &self.0, &self.1, limit)) + } +} + /// The coordinate that for duration of time #[derive(Clone)] pub struct RangedDuration(Duration, Duration); @@ -776,7 +828,7 @@ impl Ranged for RangedDuration { #[allow(clippy::inconsistent_digit_grouping)] fn compute_period_per_point(total_ns: u64, max_points: usize, sub_daily: bool) -> Option { let min_ns_per_point = total_ns as f64 / max_points as f64; - let actual_ns_per_point: u64 = (10u64).pow((min_ns_per_point as f64).log10().floor() as u32); + let actual_ns_per_point: u64 = (10u64).pow(min_ns_per_point.log10().floor() as u32); fn determine_actual_ns_per_point( total_ns: u64, @@ -798,7 +850,7 @@ fn compute_period_per_point(total_ns: u64, max_points: usize, sub_daily: bool) - if actual_ns_per_point < 1_000_000_000 { Some(determine_actual_ns_per_point( - total_ns as u64, + total_ns, actual_ns_per_point, &[1, 2, 5], 10, @@ -806,7 +858,7 @@ fn compute_period_per_point(total_ns: u64, max_points: usize, sub_daily: bool) - )) } else if actual_ns_per_point < 3600_000_000_000 { Some(determine_actual_ns_per_point( - total_ns as u64, + total_ns, 1_000_000_000, &[1, 2, 5, 10, 15, 20, 30], 60, @@ -814,7 +866,7 @@ fn compute_period_per_point(total_ns: u64, max_points: usize, sub_daily: bool) - )) } else if actual_ns_per_point < 3600_000_000_000 * 24 { Some(determine_actual_ns_per_point( - total_ns as u64, + total_ns, 3600_000_000_000, &[1, 2, 4, 8, 12], 24, @@ -823,7 +875,7 @@ fn compute_period_per_point(total_ns: u64, max_points: usize, sub_daily: bool) - } else if !sub_daily { if actual_ns_per_point < 3600_000_000_000 * 24 * 10 { Some(determine_actual_ns_per_point( - total_ns as u64, + total_ns, 3600_000_000_000 * 24, &[1, 2, 5, 7], 10, @@ -831,7 +883,7 @@ fn compute_period_per_point(total_ns: u64, max_points: usize, sub_daily: bool) - )) } else { Some(determine_actual_ns_per_point( - total_ns as u64, + total_ns, 3600_000_000_000 * 24 * 10, &[1, 2, 5], 10, @@ -1063,7 +1115,7 @@ mod test { #[test] fn test_datetime_nano_range() { let start = Utc.ymd(2019, 1, 1).and_hms(0, 0, 0); - let end = start.clone() + Duration::nanoseconds(100); + let end = start + Duration::nanoseconds(100); let coord: RangedDateTime<_> = (start..end).into(); let kps = coord.key_points(50); @@ -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> = (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 = (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/plotters/src/coord/ranged1d/types/mod.rs b/plotters/src/coord/ranged1d/types/mod.rs index 5a5ca483..1bcc0157 100644 --- a/plotters/src/coord/ranged1d/types/mod.rs +++ b/plotters/src/coord/ranged1d/types/mod.rs @@ -1,6 +1,7 @@ #[cfg(feature = "chrono")] mod datetime; #[cfg(feature = "chrono")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "chrono")))] pub use datetime::{ IntoMonthly, IntoYearly, Monthly, RangedDate, RangedDateTime, RangedDuration, Yearly, }; diff --git a/plotters/src/coord/ranged1d/types/numeric.rs b/plotters/src/coord/ranged1d/types/numeric.rs index a4e7b2b6..b76ea778 100644 --- a/plotters/src/coord/ranged1d/types/numeric.rs +++ b/plotters/src/coord/ranged1d/types/numeric.rs @@ -354,14 +354,14 @@ mod test { fn test_key_points() { let kp = compute_i32_key_points((0, 999), 28); - assert!(kp.len() > 0); + assert!(!kp.is_empty()); assert!(kp.len() <= 28); let kp = compute_f64_key_points((-1.2, 1.2), 1); assert!(kp.len() == 1); let kp = compute_f64_key_points((-1.2, 1.2), 0); - assert!(kp.len() == 0); + assert!(kp.is_empty()); } #[test] @@ -404,7 +404,7 @@ mod test { fn test_small_coord() { let coord: RangedCoordf64 = (0.0..1e-25).into(); let points = coord.key_points(10); - assert!(points.len() > 0); + assert!(!points.is_empty()); } #[test] @@ -448,6 +448,6 @@ mod test { fn regression_test_issue_304_intmax_keypoint_no_panic() { let coord: RangedCoordu32 = (0..u32::MAX).into(); let p = coord.key_points(10); - assert!(p.len() > 0 && p.len() <= 10); + assert!(!p.is_empty() && p.len() <= 10); } } diff --git a/plotters/src/drawing/area.rs b/plotters/src/drawing/area.rs index 2e5c3fe3..da8622c3 100644 --- a/plotters/src/drawing/area.rs +++ b/plotters/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 @@ -115,9 +113,9 @@ impl Rect { /// The abstraction of a drawing area. Plotters uses drawing area as the fundamental abstraction for the /// high level drawing API. The major functionality provided by the drawing area is -/// 1. Layout specification - Split the parent drawing area into sub-drawing-areas -/// 2. Coordinate Translation - Allows guest coordinate system attached and used for drawing. -/// 3. Element based drawing - drawing area provides the environment the element can be drawn onto it. +/// 1. Layout specification - Split the parent drawing area into sub-drawing-areas +/// 2. Coordinate Translation - Allows guest coordinate system attached and used for drawing. +/// 3. Element based drawing - drawing area provides the environment the element can be drawn onto it. pub struct DrawingArea { backend: Rc>, rect: Rect, @@ -550,7 +548,7 @@ mod drawing_area_tests { let drawing_area = create_mocked_drawing_area(1024, 768, |m| { m.check_draw_rect(|c, _, f, u, d| { assert_eq!(c, WHITE.to_rgba()); - assert_eq!(f, true); + assert!(f); assert_eq!(u, (0, 0)); assert_eq!(d, (1024, 768)); }); @@ -575,7 +573,7 @@ mod drawing_area_tests { let colors = colors.clone(); m.check_draw_rect(move |c, _, f, u, d| { assert_eq!(c, colors[col * 3 + row].to_rgba()); - assert_eq!(f, true); + assert!(f); assert_eq!(u, (300 * row as i32 + 2.min(row) as i32, 300 * col as i32)); assert_eq!( d, @@ -607,14 +605,14 @@ mod drawing_area_tests { let drawing_area = create_mocked_drawing_area(1024, 768, |m| { m.check_draw_rect(|c, _, f, u, d| { assert_eq!(c, RED.to_rgba()); - assert_eq!(f, true); + assert!(f); assert_eq!(u, (0, 0)); assert_eq!(d, (345, 768)); }); m.check_draw_rect(|c, _, f, u, d| { assert_eq!(c, BLUE.to_rgba()); - assert_eq!(f, true); + assert!(f); assert_eq!(u, (345, 0)); assert_eq!(d, (1024, 768)); }); @@ -635,14 +633,14 @@ mod drawing_area_tests { let drawing_area = create_mocked_drawing_area(1024, 768, |m| { m.check_draw_rect(|c, _, f, u, d| { assert_eq!(c, RED.to_rgba()); - assert_eq!(f, true); + assert!(f); assert_eq!(u, (0, 0)); assert_eq!(d, (1024, 345)); }); m.check_draw_rect(|c, _, f, u, d| { assert_eq!(c, BLUE.to_rgba()); - assert_eq!(f, true); + assert!(f); assert_eq!(u, (0, 345)); assert_eq!(d, (1024, 768)); }); @@ -660,7 +658,7 @@ mod drawing_area_tests { #[test] fn test_split_grid() { - let colors = vec![ + let colors = [ &RED, &BLUE, &YELLOW, &WHITE, &BLACK, &MAGENTA, &CYAN, &BLUE, &RED, ]; let breaks: [i32; 5] = [100, 200, 300, 400, 500]; @@ -677,7 +675,7 @@ mod drawing_area_tests { full } else { breaks[id as usize - 1] - }) as i32 + }) }; let expected_u = (get_bp(1024, nxb, col), get_bp(768, nyb, row)); @@ -688,7 +686,7 @@ mod drawing_area_tests { m.check_draw_rect(move |c, _, f, u, d| { assert_eq!(c, expected_color.to_rgba()); - assert_eq!(f, true); + assert!(f); assert_eq!(u, expected_u); assert_eq!(d, expected_d); }); @@ -722,7 +720,7 @@ mod drawing_area_tests { }); m.check_draw_rect(|c, _, f, u, d| { assert_eq!(c, WHITE.to_rgba()); - assert_eq!(f, true); + assert!(f); assert_eq!(u.0, 0); assert!(u.1 > 0); assert_eq!(d, (1024, 768)); @@ -746,7 +744,7 @@ mod drawing_area_tests { let drawing_area = create_mocked_drawing_area(1024, 768, |m| { m.check_draw_rect(|c, _, f, u, d| { assert_eq!(c, WHITE.to_rgba()); - assert_eq!(f, true); + assert!(f); assert_eq!(u, (3, 1)); assert_eq!(d, (1024 - 4, 768 - 2)); }); @@ -797,7 +795,7 @@ mod drawing_area_tests { let drawing_area = create_mocked_drawing_area(1000, 1200, |m| { let mut counter = 0; m.check_draw_rect(move |c, _, f, u, d| { - assert_eq!(f, true); + assert!(f); match counter { 0 => { diff --git a/plotters/src/element/basic_shapes.rs b/plotters/src/element/basic_shapes.rs index 7c0b9d4f..3c2564ec 100644 --- a/plotters/src/element/basic_shapes.rs +++ b/plotters/src/element/basic_shapes.rs @@ -2,6 +2,16 @@ use super::{Drawable, PointCollection}; use crate::style::{Color, ShapeStyle, SizeDesc}; use plotters_backend::{BackendCoord, DrawingBackend, DrawingErrorKind}; +#[inline] +fn to_i((x, y): (f32, f32)) -> (i32, i32) { + (x.round() as i32, y.round() as i32) +} + +#[inline] +fn to_f((x, y): (i32, i32)) -> (f32, f32) { + (x as f32, y as f32) +} + /** An element representing a single pixel. @@ -64,7 +74,7 @@ fn test_pixel_element() { assert_eq!(b.draw_count, 1); }); }); - da.draw(&Pixel::new((150, 152), &RED)) + da.draw(&Pixel::new((150, 152), RED)) .expect("Drawing Failure"); } @@ -126,7 +136,255 @@ fn test_path_element() { }); da.draw(&PathElement::new( vec![(100, 101), (105, 107), (150, 157)], - Into::::into(&BLUE).stroke_width(5), + Into::::into(BLUE).stroke_width(5), + )) + .expect("Drawing Failure"); +} + +/// An element of a series of connected lines in dash style. +/// +/// It's similar to [`PathElement`] but has a dash style. +pub struct DashedPathElement { + points: I, + size: Size, + spacing: Size, + style: ShapeStyle, +} + +impl DashedPathElement { + /// Create a new path + /// - `points`: The iterator of the points + /// - `size`: The dash size + /// - `spacing`: The dash-to-dash spacing (gap size) + /// - `style`: The shape style + /// - returns the created element + pub fn new(points: I0, size: Size, spacing: Size, style: S) -> Self + where + I0: IntoIterator, + S: Into, + { + Self { + points: points.into_iter(), + size, + spacing, + style: style.into(), + } + } +} + +impl<'a, I: Iterator + Clone, Size: SizeDesc> PointCollection<'a, I::Item> + for &'a DashedPathElement +{ + type Point = I::Item; + type IntoIter = I; + fn point_iter(self) -> Self::IntoIter { + self.points.clone() + } +} + +impl Drawable + for DashedPathElement +{ + fn draw>( + &self, + mut points: I, + backend: &mut DB, + ps: (u32, u32), + ) -> Result<(), DrawingErrorKind> { + let mut start = match points.next() { + Some(c) => to_f(c), + None => return Ok(()), + }; + let size = self.size.in_pixels(&ps).max(0) as f32; + if size == 0. { + return Ok(()); + } + let spacing = self.spacing.in_pixels(&ps).max(0) as f32; + let mut dist = 0.; + let mut is_solid = true; + let mut queue = vec![to_i(start)]; + for curr in points { + let end = to_f(curr); + // Loop for solid and spacing + while start != end { + let (dx, dy) = (end.0 - start.0, end.1 - start.1); + let d = dx.hypot(dy); + let size = if is_solid { size } else { spacing }; + let left = size - dist; + // Set next point to `start` + if left < d { + let t = left / d; + start = (start.0 + dx * t, start.1 + dy * t); + dist += left; + } else { + start = end; + dist += d; + } + // Draw if needed + if is_solid { + queue.push(to_i(start)); + } + if size <= dist { + if is_solid { + backend.draw_path(queue.drain(..), &self.style)?; + } else { + queue.push(to_i(start)); + } + dist = 0.; + is_solid = !is_solid; + } + } + } + if queue.len() > 1 { + backend.draw_path(queue, &self.style)?; + } + Ok(()) + } +} + +#[cfg(test)] +#[test] +fn test_dashed_path_element() { + use crate::prelude::*; + let check_list = std::cell::RefCell::new(vec![ + vec![(100, 100), (100, 103), (100, 105)], + vec![(100, 107), (100, 112)], + vec![(100, 114), (100, 119)], + vec![(100, 119), (100, 120)], + ]); + let da = crate::create_mocked_drawing_area(300, 300, |m| { + m.check_draw_path(move |c, s, path| { + assert_eq!(c, BLUE.to_rgba()); + assert_eq!(s, 7); + assert_eq!(path, check_list.borrow_mut().remove(0)); + }); + m.drop_check(|b| { + assert_eq!(b.num_draw_path_call, 3); + assert_eq!(b.draw_count, 3); + }); + }); + da.draw(&DashedPathElement::new( + vec![(100, 100), (100, 103), (100, 120)], + 5., + 2., + BLUE.stroke_width(7), + )) + .expect("Drawing Failure"); +} + +/// An element of a series of connected lines in dot style for any markers. +/// +/// It's similar to [`PathElement`] but use a marker function to draw markers with spacing. +pub struct DottedPathElement { + points: I, + shift: Size, + spacing: Size, + func: Box Marker>, +} + +impl DottedPathElement { + /// Create a new path + /// - `points`: The iterator of the points + /// - `shift`: The shift of the first marker + /// - `spacing`: The spacing between markers + /// - `func`: The marker function + /// - returns the created element + pub fn new(points: I0, shift: Size, spacing: Size, func: F) -> Self + where + I0: IntoIterator, + F: Fn(BackendCoord) -> Marker + 'static, + { + Self { + points: points.into_iter(), + shift, + spacing, + func: Box::new(func), + } + } +} + +impl<'a, I: Iterator + Clone, Size: SizeDesc, Marker> PointCollection<'a, I::Item> + for &'a DottedPathElement +{ + type Point = I::Item; + type IntoIter = I; + fn point_iter(self) -> Self::IntoIter { + self.points.clone() + } +} + +impl Drawable for DottedPathElement +where + I0: Iterator + Clone, + Size: SizeDesc, + DB: DrawingBackend, + Marker: crate::element::IntoDynElement<'static, DB, BackendCoord>, +{ + fn draw>( + &self, + mut points: I, + backend: &mut DB, + ps: (u32, u32), + ) -> Result<(), DrawingErrorKind> { + let mut shift = self.shift.in_pixels(&ps).max(0) as f32; + let mut start = match points.next() { + Some(start_i) => { + // Draw the first marker if no shift + if shift == 0. { + let mk = (self.func)(start_i).into_dyn(); + mk.draw(mk.point_iter().iter().copied(), backend, ps)?; + } + to_f(start_i) + } + None => return Ok(()), + }; + let spacing = self.spacing.in_pixels(&ps).max(0) as f32; + let mut dist = 0.; + for curr in points { + let end = to_f(curr); + // Loop for spacing + while start != end { + let (dx, dy) = (end.0 - start.0, end.1 - start.1); + let d = dx.hypot(dy); + let spacing = if shift == 0. { spacing } else { shift }; + let left = spacing - dist; + // Set next point to `start` + if left < d { + let t = left / d; + start = (start.0 + dx * t, start.1 + dy * t); + dist += left; + } else { + start = end; + dist += d; + } + // Draw if needed + if spacing <= dist { + let mk = (self.func)(to_i(start)).into_dyn(); + mk.draw(mk.point_iter().iter().copied(), backend, ps)?; + shift = 0.; + dist = 0.; + } + } + } + Ok(()) + } +} + +#[cfg(test)] +#[test] +fn test_dotted_path_element() { + use crate::prelude::*; + let da = crate::create_mocked_drawing_area(300, 300, |m| { + m.drop_check(|b| { + assert_eq!(b.num_draw_path_call, 0); + assert_eq!(b.draw_count, 7); + }); + }); + da.draw(&DottedPathElement::new( + vec![(100, 100), (105, 105), (150, 150)], + 5, + 10, + |c| Circle::new(c, 5, Into::::into(RED).filled()), )) .expect("Drawing Failure"); } @@ -199,7 +457,7 @@ fn test_rect_element() { let da = crate::create_mocked_drawing_area(300, 300, |m| { m.check_draw_rect(|c, s, f, u, d| { assert_eq!(c, BLUE.to_rgba()); - assert_eq!(f, false); + assert!(!f); assert_eq!(s, 5); assert_eq!([u, d], [(100, 101), (105, 107)]); }); @@ -219,7 +477,7 @@ fn test_rect_element() { let da = crate::create_mocked_drawing_area(300, 300, |m| { m.check_draw_rect(|c, _, f, u, d| { assert_eq!(c, BLUE.to_rgba()); - assert_eq!(f, true); + assert!(f); assert_eq!([u, d], [(100, 101), (105, 107)]); }); m.drop_check(|b| { @@ -284,7 +542,7 @@ fn test_circle_element() { let da = crate::create_mocked_drawing_area(300, 300, |m| { m.check_draw_circle(|c, _, f, s, r| { assert_eq!(c, BLUE.to_rgba()); - assert_eq!(f, false); + assert!(!f); assert_eq!(s, (150, 151)); assert_eq!(r, 20); }); @@ -293,7 +551,7 @@ fn test_circle_element() { assert_eq!(b.draw_count, 1); }); }); - da.draw(&Circle::new((150, 151), 20, &BLUE)) + da.draw(&Circle::new((150, 151), 20, BLUE)) .expect("Drawing Failure"); } @@ -353,6 +611,6 @@ fn test_polygon_element() { }); }); - da.draw(&Polygon::new(points.clone(), &BLUE)) + da.draw(&Polygon::new(points.clone(), BLUE)) .expect("Drawing Failure"); } diff --git a/plotters/src/element/boxplot.rs b/plotters/src/element/boxplot.rs index 2de2bd06..2ba20e3c 100644 --- a/plotters/src/element/boxplot.rs +++ b/plotters/src/element/boxplot.rs @@ -74,7 +74,7 @@ impl Boxplot> { /// ``` pub fn new_vertical(key: K, quartiles: &Quartiles) -> Self { Self { - style: Into::::into(&BLACK), + style: Into::::into(BLACK), width: DEFAULT_WIDTH, whisker_width: 1.0, offset: 0.0, @@ -100,7 +100,7 @@ impl Boxplot> { /// ``` pub fn new_horizontal(key: K, quartiles: &Quartiles) -> Self { Self { - style: Into::::into(&BLACK), + style: Into::::into(BLACK), width: DEFAULT_WIDTH, whisker_width: 1.0, offset: 0.0, diff --git a/plotters/src/element/mod.rs b/plotters/src/element/mod.rs index e2790051..849f8ae4 100644 --- a/plotters/src/element/mod.rs +++ b/plotters/src/element/mod.rs @@ -175,21 +175,25 @@ pub use composable::{ComposedElement, EmptyElement}; #[cfg(feature = "candlestick")] mod candlestick; #[cfg(feature = "candlestick")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "candlestick")))] pub use candlestick::CandleStick; #[cfg(feature = "errorbar")] mod errorbar; #[cfg(feature = "errorbar")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "errorbar")))] pub use errorbar::{ErrorBar, ErrorBarOrientH, ErrorBarOrientV}; #[cfg(feature = "boxplot")] mod boxplot; #[cfg(feature = "boxplot")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "boxplot")))] pub use boxplot::Boxplot; #[cfg(feature = "bitmap_backend")] mod image; #[cfg(feature = "bitmap_backend")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "bitmap_backend")))] pub use self::image::BitMapElement; mod dynelem; diff --git a/plotters/src/element/pie.rs b/plotters/src/element/pie.rs index 95298345..cf61c63d 100644 --- a/plotters/src/element/pie.rs +++ b/plotters/src/element/pie.rs @@ -31,6 +31,7 @@ pub struct Pie<'a, Coord, Label: Display> { label_style: TextStyle<'a>, label_offset: f64, percentage_style: Option>, + donut_hole: f64, // radius of the hole in case of a donut chart } impl<'a, Label: Display> Pie<'a, (i32, i32), Label> { @@ -62,6 +63,7 @@ impl<'a, Label: Display> Pie<'a, (i32, i32), Label> { label_style, label_offset: radius_5pct, percentage_style: None, + donut_hole: 0.0, } } @@ -91,6 +93,15 @@ impl<'a, Label: Display> Pie<'a, (i32, i32), Label> { pub fn percentages>>(&mut self, label_style: T) { self.percentage_style = Some(label_style.into()); } + + /// Enables creating a donut chart with a hole of the specified radius. + /// + /// The passed value must be greater than zero and lower than the chart overall radius, otherwise it'll be ignored. + pub fn donut_hole(&mut self, hole_radius: f64) { + if hole_radius > 0.0 && hole_radius < *self.radius { + self.donut_hole = hole_radius; + } + } } impl<'a, DB: DrawingBackend, Label: Display> Drawable for Pie<'a, (i32, i32), Label> { @@ -109,26 +120,28 @@ impl<'a, DB: DrawingBackend, Label: Display> Drawable 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 mut points = if self.donut_hole == 0.0 { + vec![*self.center] + } else { + vec![] + }; let ratio = slice / self.total; let theta_final = ratio * 2.0 * PI + offset_theta; // end radian for the wedge // calculate middle for labels before mutating offset let middle_theta = ratio * PI + offset_theta; + let slice_start = offset_theta; + // calculate every fraction of radian for the wedge, offsetting for every iteration, clockwise // // a custom Range such as `for theta in offset_theta..=theta_final` would be more elegant @@ -142,6 +155,19 @@ impl<'a, DB: DrawingBackend, Label: Display> Drawable for Pie<'a, (i32, i32) // final point of the wedge may not fall exactly on a radian, so add it extra let final_coord = theta_to_ordinal_coord(*self.radius, theta_final, self.center); points.push(final_coord); + + if self.donut_hole > 0.0 { + while offset_theta >= slice_start { + let coord = theta_to_ordinal_coord(self.donut_hole, offset_theta, self.center); + points.push(coord); + offset_theta -= radian_increment; + } + // final point of the wedge may not fall exactly on a radian, so add it extra + let final_coord_inner = + theta_to_ordinal_coord(self.donut_hole, slice_start, self.center); + points.push(final_coord_inner); + } + // next wedge calculation will start from previous wedges's last radian offset_theta = theta_final; @@ -167,8 +193,9 @@ impl<'a, DB: DrawingBackend, Label: Display> Drawable for Pie<'a, (i32, i32) let label_size = backend.estimate_text_size(&perc_label, percentage_style)?; let text_x_mid = (label_size.0 as f64 / 2.0).round() as i32; let text_y_mid = (label_size.1 as f64 / 2.0).round() as i32; + let perc_radius = (self.radius + self.donut_hole) / 2.0; let perc_coord = theta_to_ordinal_coord( - self.radius / 2.0, + perc_radius, middle_theta, &(self.center.0 - text_x_mid, self.center.1 - text_y_mid), ); @@ -234,7 +261,7 @@ mod test { center.1 += 1; radius += 1.0; assert!(colors.get(0).is_none()); - assert!(labels.get(0).is_none()); + assert!(labels.first().is_none()); assert_eq!(radius, 801.0); } } diff --git a/plotters/src/evcxr.rs b/plotters/src/evcxr.rs index 8117d35f..921282f3 100644 --- a/plotters/src/evcxr.rs +++ b/plotters/src/evcxr.rs @@ -4,6 +4,7 @@ use plotters_backend::DrawingBackend; use plotters_svg::SVGBackend; #[cfg(feature = "evcxr_bitmap")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "evcxr_bitmap")))] use plotters_bitmap::BitMapBackend; /// The wrapper for the generated SVG @@ -47,13 +48,14 @@ pub fn evcxr_figure< /// Start drawing an evcxr figure #[cfg(feature = "evcxr_bitmap")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "evcxr_bitmap")))] pub fn evcxr_bitmap_figure< Draw: FnOnce(DrawingArea) -> Result<(), Box>, >( 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/plotters/src/lib.rs b/plotters/src/lib.rs index 873288b2..d1dfdacd 100644 --- a/plotters/src/lib.rs +++ b/plotters/src/lib.rs @@ -1,7 +1,8 @@ #![warn(missing_docs)] +#![cfg_attr(doc_cfg, feature(doc_cfg))] /*! -# 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 🦀📈🚀 @@ -16,14 +17,14 @@ -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 +35,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Multiple Plot - [code] + [code]
@@ -44,7 +45,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Candlestick Plot - [code] + [code]
@@ -54,7 +55,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Histogram - [code] + [code]
@@ -82,7 +83,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Mandelbrot set - [code] + [code]
@@ -112,7 +113,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Histogram with Scatter - [code] + [code]
@@ -122,7 +123,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Dual Y-Axis Example - [code] + [code]
@@ -132,7 +133,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
The Matplotlib Matshow Example - [code] + [code]
@@ -142,7 +143,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
The Sierpinski Carpet - [code] + [code]
@@ -152,7 +153,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
The 1D Gaussian Distribution - [code] + [code]
@@ -162,7 +163,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
The 1D Gaussian Distribution - [code] + [code]
@@ -172,7 +173,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Monthly Time Coordinate - [code] + [code]
@@ -182,7 +183,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Monthly Time Coordinate - [code] + [code]
@@ -192,7 +193,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Koch Snowflake - [code] + [code]
@@ -203,7 +204,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Koch Snowflake Animation - [code] + [code]
@@ -214,7 +215,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Drawing on a Console - [code] + [code]
@@ -224,7 +225,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Drawing bitmap on chart - [code] + [code]
@@ -234,7 +235,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
The boxplot demo - [code] + [code]
@@ -244,7 +245,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
3D plot rendering - [code] + [code]
@@ -254,7 +255,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
2-Var Gussian Distribution PDF - [code] + [code]
@@ -264,7 +265,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
COVID-19 Visualization - [code] + [code]
@@ -280,8 +281,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 +304,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 +347,27 @@ fn main() -> Result<(), Box> { ## 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 +397,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 +407,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 +474,10 @@ fn main() -> Result<(), Box> { ### 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 +499,7 @@ fn main() -> Result<(), Box> { ### 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 +527,9 @@ fn main() -> Result<(), Box> { ### 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 +570,7 @@ fn main() -> Result<(), Box> { ### 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 +581,7 @@ fn main() -> Result<(), Box> { 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 +628,14 @@ fn main() -> Result<(), Box> { ### 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 +649,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 +662,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 +743,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 +757,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. @@ -769,12 +797,14 @@ pub mod style; /// Evaluation Context for Rust. See [the evcxr crate](https://crates.io/crates/evcxr) for more information. #[cfg(feature = "evcxr")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "evcxr")))] pub mod evcxr; #[cfg(test)] pub use crate::drawing::{check_color, create_mocked_drawing_area}; #[cfg(feature = "palette_ext")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "palette_ext")))] pub use palette; /// The module imports the most commonly used types and modules in Plotters @@ -798,6 +828,7 @@ pub mod prelude { pub use crate::coord::combinators::LogRange; #[cfg(feature = "chrono")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "chrono")))] pub use crate::coord::types::{ IntoMonthly, IntoYearly, RangedDate, RangedDateTime, RangedDuration, }; @@ -809,22 +840,32 @@ pub mod prelude { // Series helpers #[cfg(feature = "area_series")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "area_series")))] pub use crate::series::AreaSeries; #[cfg(feature = "histogram")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "histogram")))] pub use crate::series::Histogram; - #[cfg(feature = "line_series")] - pub use crate::series::LineSeries; #[cfg(feature = "point_series")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "point_series")))] pub use crate::series::PointSeries; #[cfg(feature = "surface_series")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "surface_series")))] pub use crate::series::SurfaceSeries; + #[cfg(feature = "line_series")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "line_series")))] + pub use crate::series::{DashedLineSeries, DottedLineSeries, LineSeries}; // Styles pub use crate::style::{BLACK, BLUE, CYAN, GREEN, MAGENTA, RED, TRANSPARENT, WHITE, YELLOW}; #[cfg(feature = "full_palette")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "full_palette")))] pub use crate::style::full_palette; + #[cfg(feature = "colormaps")] + #[cfg_attr(doc_cfg, doc(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, @@ -838,13 +879,17 @@ pub mod prelude { }; #[cfg(feature = "boxplot")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "boxplot")))] pub use crate::element::Boxplot; #[cfg(feature = "candlestick")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "candlestick")))] pub use crate::element::CandleStick; #[cfg(feature = "errorbar")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "errorbar")))] pub use crate::element::ErrorBar; #[cfg(feature = "bitmap_backend")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "bitmap_backend")))] pub use crate::element::BitMapElement; // Data @@ -852,6 +897,7 @@ pub mod prelude { // TODO: This should be deprecated and completely removed #[cfg(feature = "deprecated_items")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "deprecated_items")))] #[allow(deprecated)] pub use crate::element::Path; @@ -863,13 +909,16 @@ pub mod prelude { Result>; #[cfg(feature = "evcxr")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "evcxr")))] pub use crate::evcxr::evcxr_figure; // Re-export tier 1 backends for backward compatibility #[cfg(feature = "bitmap_backend")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "bitmap_backend")))] pub use plotters_bitmap::BitMapBackend; #[cfg(feature = "svg_backend")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "svg_backend")))] pub use plotters_svg::SVGBackend; } @@ -877,11 +926,13 @@ pub mod prelude { pub mod backend { pub use plotters_backend::DrawingBackend; #[cfg(feature = "bitmap_backend")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "bitmap_backend")))] pub use plotters_bitmap::{ bitmap_pixel::{BGRXPixel, PixelFormat, RGBPixel}, BitMapBackend, }; #[cfg(feature = "svg_backend")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "svg_backend")))] pub use plotters_svg::SVGBackend; } diff --git a/plotters/src/series/histogram.rs b/plotters/src/series/histogram.rs index 2d7d8f48..2574727f 100644 --- a/plotters/src/series/histogram.rs +++ b/plotters/src/series/histogram.rs @@ -180,7 +180,7 @@ where let mut buffer = HashMap::::new(); for (x, y) in iter.into_iter() { if let Some(x) = self.br.index_of(&x.into()) { - *buffer.entry(x).or_insert_with(Default::default) += y; + *buffer.entry(x).or_default() += y; } } self.iter = buffer.into_iter(); diff --git a/plotters/src/series/line_series.rs b/plotters/src/series/line_series.rs index 2d0cf986..2e67503b 100644 --- a/plotters/src/series/line_series.rs +++ b/plotters/src/series/line_series.rs @@ -1,6 +1,8 @@ -use crate::element::{Circle, DynElement, IntoDynElement, PathElement}; -use crate::style::ShapeStyle; -use plotters_backend::DrawingBackend; +use crate::element::{ + Circle, DashedPathElement, DottedPathElement, DynElement, IntoDynElement, PathElement, +}; +use crate::style::{ShapeStyle, SizeDesc}; +use plotters_backend::{BackendCoord, DrawingBackend}; use std::marker::PhantomData; /** @@ -45,8 +47,7 @@ impl Iterator for LineSeries LineSeries { } } +/// A dashed line series, map an iterable object to the dashed line element. +pub struct DashedLineSeries { + points: I, + size: Size, + spacing: Size, + style: ShapeStyle, +} + +impl DashedLineSeries { + /// Create a new line series from + /// - `points`: The iterator of the points + /// - `size`: The dash size + /// - `spacing`: The dash-to-dash spacing (gap size) + /// - `style`: The shape style + /// - returns the created element + pub fn new(points: I0, size: Size, spacing: Size, style: ShapeStyle) -> Self + where + I0: IntoIterator, + { + Self { + points: points.into_iter(), + size, + spacing, + style, + } + } +} + +impl IntoIterator for DashedLineSeries { + type Item = DashedPathElement; + type IntoIter = std::iter::Once; + + fn into_iter(self) -> Self::IntoIter { + std::iter::once(DashedPathElement::new( + self.points, + self.size, + self.spacing, + self.style, + )) + } +} + +/// A dotted line series, map an iterable object to the dotted line element. +pub struct DottedLineSeries { + points: I, + shift: Size, + spacing: Size, + func: Box Marker>, +} + +impl DottedLineSeries { + /// Create a new line series from + /// - `points`: The iterator of the points + /// - `shift`: The shift of the first marker + /// - `spacing`: The spacing between markers + /// - `func`: The marker function + /// - returns the created element + pub fn new(points: I0, shift: Size, spacing: Size, func: F) -> Self + where + I0: IntoIterator, + F: Fn(BackendCoord) -> Marker + 'static, + { + Self { + points: points.into_iter(), + shift, + spacing, + func: Box::new(func), + } + } +} + +impl IntoIterator + for DottedLineSeries +{ + type Item = DottedPathElement; + type IntoIter = std::iter::Once; + + fn into_iter(self) -> Self::IntoIter { + std::iter::once(DottedPathElement::new( + self.points, + self.shift, + self.spacing, + self.func, + )) + } +} + #[cfg(test)] mod test { use crate::prelude::*; @@ -103,8 +191,8 @@ mod test { }); m.drop_check(|b| { - assert_eq!(b.num_draw_path_call, 1); - assert_eq!(b.draw_count, 1); + assert_eq!(b.num_draw_path_call, 8); + assert_eq!(b.draw_count, 27); }); }); @@ -115,8 +203,20 @@ mod test { chart .draw_series(LineSeries::new( (0..100).map(|x| (x, x)), - Into::::into(&RED).stroke_width(3), + Into::::into(RED).stroke_width(3), )) .expect("Drawing Error"); + chart + .draw_series(DashedLineSeries::new( + (0..=50).map(|x| (0, x)), + 10, + 5, + Into::::into(RED).stroke_width(3), + )) + .expect("Drawing Error"); + let mk_f = |c| Circle::new(c, 3, Into::::into(RED).filled()); + chart + .draw_series(DottedLineSeries::new((0..=50).map(|x| (x, 0)), 5, 5, mk_f)) + .expect("Drawing Error"); } } diff --git a/plotters/src/series/mod.rs b/plotters/src/series/mod.rs index a0c8f198..706bd211 100644 --- a/plotters/src/series/mod.rs +++ b/plotters/src/series/mod.rs @@ -22,12 +22,17 @@ mod point_series; mod surface; #[cfg(feature = "area_series")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "area_series")))] pub use area_series::AreaSeries; #[cfg(feature = "histogram")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "histogram")))] pub use histogram::Histogram; #[cfg(feature = "line_series")] -pub use line_series::LineSeries; +#[cfg_attr(doc_cfg, doc(cfg(feature = "line_series")))] +pub use line_series::{DashedLineSeries, DottedLineSeries, LineSeries}; #[cfg(feature = "point_series")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "point_series")))] pub use point_series::PointSeries; #[cfg(feature = "surface_series")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "surface_series")))] pub use surface::SurfaceSeries; diff --git a/plotters/src/style/colors/colormaps.rs b/plotters/src/style/colors/colormaps.rs new file mode 100644 index 00000000..a320502c --- /dev/null +++ b/plotters/src/style/colors/colormaps.rs @@ -0,0 +1,370 @@ +use crate::style::{HSLColor, RGBAColor, RGBColor}; + +/// Converts scalar values to colors. +pub trait ColorMap +where + FloatType: num_traits::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 { + colors: Vec, +} + +impl DerivedColorMap { + /// 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_export] +#[doc(hidden)] +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(), + ) + }; +); + +// Helper function to calculate the lower and upper index nearest to a provided float value. +// +// Used to obtain colors from a colorscale given a value h between 0.0 and 1.0. +// It also returns the relative difference which can then be used to calculate a linear interpolation between the two nearest colors. +// ``` +// # use plotters::prelude::*; +// let r = calculate_relative_difference_index_lower_upper(1.2, 1.0, 3.0, 4); +// let (relative_difference, lower_index, upper_index) = r; +// +// assert_eq!(relative_difference, 0.7000000000000001); +// assert_eq!(lower_index, 0); +// assert_eq!(upper_index, 1); +// ``` +#[doc(hidden)] +pub fn calculate_relative_difference_index_lower_upper< + FloatType: num_traits::Float + num_traits::FromPrimitive + num_traits::ToPrimitive, +>( + h: FloatType, + min: FloatType, + max: FloatType, + n_steps: 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_steps).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 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 + $crate::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_export] +#[doc(hidden)] +// Counts the number of arguments which are separated by spaces +// +// This macro is used internally to determine the size of an array to hold all new colors. +// ``` +// # use plotters::count; +// let counted = count!{Plotting is fun}; +// assert_eq!(counted, 3); +// +// let counted2 = count!{0_usize was my favourite 1_f64 last century}; +// assert_eq!(counted2, 7); +// +// let new_array = ["Hello"; count!(Plotting is fun)]; +// assert_eq!(new_array, ["Hello"; 3]); +// ``` +macro_rules! count { + () => (0usize); + ($x:tt $($xs:tt)* ) => (1usize + $crate::count!($($xs)*)); +} + +#[macro_export] +#[doc(hidden)] +/// Converts a given color identifier and a sequence of colors to an array of them. +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_export] +#[doc(hidden)] +/// Implements the [ColorMap] trait on a given color scale. +macro_rules! implement_linear_interpolation_color_map { + ($color_scale_name:ident, $color_type:ident) => { + impl + 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 + $crate::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( + 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 + num_traits::Float + num_traits::FromPrimitive + num_traits::ToPrimitive, + >( + h: FloatType, + min: FloatType, + max: FloatType, + ) -> $color_type { + let color_scale = $color_scale_name {}; + color_scale.get_color_normalized(h, min, max) + } + } + }; +} + +#[doc(inline)] +pub use crate::def_linear_colormap; + +#[macro_export] +#[doc(hidden)] +/// Create a new colormap with evenly spaced colors and interpolates between them automatically. +/// +/// This macro works by taking a identifier (name) for the colormap, the type of color to specify, a +/// docstring and a list of colors and constructs an empty struct on which it implements the [ColorMap] trait. +/// +/// ``` +/// use plotters::prelude::*; +/// def_linear_colormap! { +/// BlackWhite, +/// RGBColor, +/// "Simple chromatic colormap from black to white.", +/// ( 0, 0, 0), +/// (255, 255, 255) +/// } +/// +/// assert_eq!(BlackWhite::get_color(0.0), RGBColor(0,0,0)); +/// ``` +/// +/// Hint: Some helper macros and functions have been deliberately hidden from end users. +/// Look for them in the source code if you are interested. +macro_rules! def_linear_colormap{ + ($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; $crate::count!($(($($color_value:expr),+))*)] = [$($color_type($($color_value),+)),+]; + const COLORS: [$color_type; $crate::count!($(($($color_value:expr),+))*)] = $crate::define_colors_from_list_of_values_or_directly!{$color_type, $(($($color_value),+)),*}; + } + + $crate::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; $crate::count!($($color_complete)*)] = $crate::define_colors_from_list_of_values_or_directly!{$($color_complete),+}; + } + + $crate::implement_linear_interpolation_color_map!{$color_scale_name, $color_type} + } +} + +def_linear_colormap! { + 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) +} + +def_linear_colormap! { + 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) +} + +def_linear_colormap! { + BlackWhite, + RGBColor, + "Simple chromatic colormap from black to white.", + ( 0, 0, 0), + (255, 255, 255) +} + +def_linear_colormap! { + 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) +} + +def_linear_colormap! { + 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::*; +def_linear_colormap! { + Bone, + RGBColor, + "Dark colormap going from black over blue to white.", + BLACK, + BLUE, + WHITE +} + +def_linear_colormap! { + Copper, + RGBColor, + "Friendly black to brown colormap.", + BLACK, + BROWN, + ORANGE +} diff --git a/plotters/src/style/colors/mod.rs b/plotters/src/style/colors/mod.rs index 34448ba0..aadee70a 100644 --- a/plotters/src/style/colors/mod.rs +++ b/plotters/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,12 @@ 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")] +#[cfg_attr(doc_cfg, doc(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")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "full_palette")))] pub mod full_palette; diff --git a/plotters/src/style/font/ab_glyph.rs b/plotters/src/style/font/ab_glyph.rs new file mode 100644 index 00000000..42b43344 --- /dev/null +++ b/plotters/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>, +} +impl FontMap { + fn new() -> Self { + Self { + map: HashMap::with_capacity(4), + } + } + fn insert(&mut self, style: FontStyle, font: FontRef<'static>) -> Option> { + 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>> = 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 { + 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 { + 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 Result<(), E>>( + &self, + pos: (i32, i32), + size: f64, + text: &str, + mut draw: DrawFunc, + ) -> Result, 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/plotters/src/style/font/font_desc.rs b/plotters/src/style/font/font_desc.rs index a101a5d8..3a4ec799 100644 --- a/plotters/src/style/font/font_desc.rs +++ b/plotters/src/style/font/font_desc.rs @@ -113,7 +113,7 @@ impl<'a> FontDesc<'a> { TextStyle { font: self.clone(), color: color.to_backend_color(), - pos: Pos::default(), + pos: None, } } diff --git a/plotters/src/style/font/mod.rs b/plotters/src/style/font/mod.rs index 305978fd..d80ee289 100644 --- a/plotters/src/style/font/mod.rs +++ b/plotters/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/plotters/src/style/font/ttf.rs b/plotters/src/style/font/ttf.rs index e6feadc8..57c02cf5 100644 --- a/plotters/src/style/font/ttf.rs +++ b/plotters/src/style/font/ttf.rs @@ -82,9 +82,7 @@ impl FontExt { _ => unreachable!(), }; let face = unsafe { - std::mem::transmute::<_, Option>>( - ttf_parser::Face::from_slice(data, idx).ok(), - ) + std::mem::transmute::<_, Option>>(ttf_parser::Face::parse(data, idx).ok()) }; Self { inner: font, face } } @@ -134,12 +132,12 @@ fn load_font_data(face: FontFamily, style: FontStyle) -> FontResult { // Then we need to check if the data cache contains the font data let cache = DATA_CACHE.read().unwrap(); if let Some(data) = cache.get(Borrow::::borrow(&key)) { - return data.clone().map(|handle| { + data.clone().map(|handle| { handle .load() .map(FontExt::new) .map_err(|e| FontError::FontLoadError(Arc::new(e))) - })?; + })??; } drop(cache); @@ -268,8 +266,8 @@ impl FontData for FontDataInternal { .rasterize_glyph( &mut canvas, glyph_id, - em as f32, - Transform2F::from_translation(Vector2F::new(0.0, em as f32)), + em, + Transform2F::from_translation(Vector2F::new(0.0, em)), HintingOptions::None, RasterizationOptions::GrayscaleAa, ) @@ -316,6 +314,6 @@ mod test { // TODO: Check they are the same - return Ok(()); + Ok(()) } } diff --git a/plotters/src/style/mod.rs b/plotters/src/style/mod.rs index 7d7c9ac3..90bed9f3 100644 --- a/plotters/src/style/mod.rs +++ b/plotters/src/style/mod.rs @@ -15,11 +15,15 @@ pub use color::{Color, HSLColor, PaletteColor, RGBAColor, RGBColor}; pub use colors::{BLACK, BLUE, CYAN, GREEN, MAGENTA, RED, TRANSPARENT, WHITE, YELLOW}; #[cfg(feature = "full_palette")] +#[cfg_attr(doc_cfg, doc(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; diff --git a/plotters/src/style/text.rs b/plotters/src/style/text.rs index e98f3193..9981fd53 100644 --- a/plotters/src/style/text.rs +++ b/plotters/src/style/text.rs @@ -13,7 +13,7 @@ pub struct TextStyle<'a> { /// The text color pub color: BackendColor, /// The anchor point position - pub pos: text_anchor::Pos, + pub pos: Option, } /// Trait for values that can be converted into `TextStyle` values @@ -191,7 +191,7 @@ impl<'a> TextStyle<'a> { Self { font: self.font.clone(), color: self.color, - pos, + pos: Some(pos), } } } @@ -276,7 +276,7 @@ impl<'a, T: Into>> From for TextStyle<'a> { Self { font: font.into(), color: BLACK.to_backend_color(), - pos: text_anchor::Pos::default(), + pos: Some(text_anchor::Pos::default()), } } } @@ -304,7 +304,7 @@ impl<'a> BackendTextStyle for TextStyle<'a> { self.font.layout_box(text) } - fn anchor(&self) -> text_anchor::Pos { + fn anchor(&self) -> Option { self.pos }