diff --git a/.github/dependabot.yml b/.github/dependabot.yml index f989eef4..a8fdcc59 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -14,3 +14,7 @@ updates: - dependency-name: gif versions: - 0.11.1 +- package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "daily" diff --git a/.github/workflows/plotters-backend.yml b/.github/workflows/plotters-backend.yml index e6a5e37d..556f39b8 100644 --- a/.github/workflows/plotters-backend.yml +++ b/.github/workflows/plotters-backend.yml @@ -9,7 +9,7 @@ jobs: matrix: os: [ubuntu-latest, windows-latest, macos-latest] steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v4 with: submodules: recursive - uses: actions-rs/toolchain@v1 diff --git a/.github/workflows/plotters-bitmap.yml b/.github/workflows/plotters-bitmap.yml index 6cb86b02..79b4f259 100644 --- a/.github/workflows/plotters-bitmap.yml +++ b/.github/workflows/plotters-bitmap.yml @@ -9,7 +9,7 @@ jobs: matrix: os: [ubuntu-latest, windows-latest, macos-latest] steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v4 with: submodules: recursive - uses: actions-rs/toolchain@v1 diff --git a/.github/workflows/plotters-core.yml b/.github/workflows/plotters-core.yml index 2f53410a..1e9a952c 100644 --- a/.github/workflows/plotters-core.yml +++ b/.github/workflows/plotters-core.yml @@ -7,7 +7,7 @@ jobs: name: cargo-doc runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - uses: actions-rs/toolchain@v1 with: profile: minimal @@ -20,7 +20,7 @@ jobs: msrv: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v4 with: submodules: recursive - uses: actions-rs/toolchain@v1 @@ -34,7 +34,7 @@ jobs: matrix: os: [ubuntu-latest, windows-latest, macos-latest] steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v4 with: submodules: recursive - uses: actions-rs/toolchain@v1 @@ -52,7 +52,7 @@ jobs: test_all_features: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v4 with: submodules: recursive - uses: actions-rs/toolchain@v1 @@ -66,7 +66,7 @@ jobs: run_all_examples: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v4 with: submodules: recursive - uses: actions-rs/cargo@v1 @@ -81,7 +81,7 @@ jobs: ../target/release/examples/$(basename ${example} .rs) done tar -czvf example-outputs.tar.gz plotters-doc-data - - uses: actions/upload-artifact@v1 + - uses: actions/upload-artifact@v4 with: name: example-outputs path: plotters/example-outputs.tar.gz diff --git a/.github/workflows/plotters-svg.yml b/.github/workflows/plotters-svg.yml index d81e98f7..d44a400c 100644 --- a/.github/workflows/plotters-svg.yml +++ b/.github/workflows/plotters-svg.yml @@ -9,7 +9,7 @@ jobs: matrix: os: [ubuntu-latest, windows-latest, macos-latest] steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v4 with: submodules: recursive - uses: actions-rs/toolchain@v1 diff --git a/.github/workflows/rust-clippy.yml b/.github/workflows/rust-clippy.yml index ca1732c8..8536ab98 100644 --- a/.github/workflows/rust-clippy.yml +++ b/.github/workflows/rust-clippy.yml @@ -27,7 +27,7 @@ jobs: security-events: write steps: - name: Checkout code - uses: actions/checkout@v2 + uses: actions/checkout@v4 - name: Install Rust toolchain uses: actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af #@v1 @@ -48,7 +48,7 @@ jobs: continue-on-error: true - name: Upload analysis results to GitHub - uses: github/codeql-action/upload-sarif@v1 + uses: github/codeql-action/upload-sarif@v3 with: sarif_file: rust-clippy-results.sarif wait-for-processing: true diff --git a/.github/workflows/wasm.yml b/.github/workflows/wasm.yml index 35166ecc..e9ae4ad3 100644 --- a/.github/workflows/wasm.yml +++ b/.github/workflows/wasm.yml @@ -8,7 +8,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v4 with: submodules: recursive - name: Install WASM tool chain diff --git a/.gitignore b/.gitignore index c6695f5e..297134f4 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,5 @@ **/target .vscode/* Cargo.lock +.idea +plotters/*.svg diff --git a/CHANGELOG.md b/CHANGELOG.md index 86186ab4..664ba133 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,41 @@ # Changelog -## Plotters 0.3.4 (?) +## Plotters 0.3.6 (2024-05-20) + +### Added + +- Add Clone and PartialEq traits to SeriesLabelPosition and ShapeStyle +- Add function to draw and save an evcxr figure +- Add dotted line style + +### Fixed + +- Fix bug with infinite size for collinear line segments as coordinates +- Fix overflow in blit_bitmap +- Fix dashed line algorithm + +## 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) @@ -20,7 +55,7 @@ ### Improved -- Improved documentaiton for predefined colors. (Thanks to @siefkenj) +- Improved documentation for predefined colors. (Thanks to @siefkenj) - Introduce the full Material Design 2014 Color Palette. (Thanks to @siefkenj) - Massive documentation improvements (Thanks to @facorread and many others) @@ -39,19 +74,19 @@ ### Fixed -- Infinte loop / panic when the axis range is zero +- Infinite loop / panic when the axis range is zero - UB in minifb example (thanks to TheEdward162) - Examples that uses old APIs (thanks to chrisduerr) ## Plotters 0.3.0 (2020-09-03) -This is the next major release of Plotters, see [release notes](./RELEASE-NOTES.md) for more detials. +This is the next major release of Plotters, see [release notes](./RELEASE-NOTES.md) for more details. ### Added - The plotters backend API crate is introduced which allows third-party backend. - Allow slice used as a coordinate if the item type implements `PartialOrd`. -- Linspace coordinate type, which allows define a discrete coordinate on continous value types (such as f32, DateTime, etc) with a step specification +- Linspace coordinate type, which allows define a discrete coordinate on continuous value types (such as f32, DateTime, etc) with a step specification - Nested coordinate type, now we support define pair of category and nested values as nested coordinate. - Introduce backend crates: plotters-bitmap, plotters-svg, plotters-cairo, plotters-canvas, plotters-console - 3D Plotting features @@ -62,7 +97,7 @@ This is the next major release of Plotters, see [release notes](./RELEASE-NOTES. ### Improvement -- Enhanced key point algorithms: New key point hint trait are used for key point algorithms && many improvment on key point algorithms for different types +- Enhanced key point algorithms: New key point hint trait are used for key point algorithms && many improvement on key point algorithms for different types - Renamed `MeshStyle::line\_style\_1` and `MeshStyle::line\_style\_2` to `bold\_line\_style` and `light\_line\_style` - Reorganize the "plotters::coord" namespace - Improved discrete coordinate trait @@ -107,7 +142,7 @@ This is the next major release of Plotters, see [release notes](./RELEASE-NOTES. - Incremental Rendering by saving the previous chart context into a state and restore it on a different drawing area. - BoxPlot support (See boxplot example for more details) (Thanks to @nuald) - Category coordinate spec which allows use a list of given values as coordinate (Thanks to @nuald) -- New text positioning model which allows develvoper sepecify the anchor point. This is critical for layouting SVG correctly. See `plotters::style::text::text_anchor` for details. (Thanks to @nuald) +- New text positioning model which allows develvoper specify the anchor point. This is critical for layouting SVG correctly. See `plotters::style::text::text_anchor` for details. (Thanks to @nuald) ### Improved @@ -126,9 +161,9 @@ This is the next major release of Plotters, see [release notes](./RELEASE-NOTES. - Font description is greatly improved, general font family is supported: `serif`, `serif-sans`, `monospace` (Thanks to @Tatrix) - Tested the font loading on Linux, OSX and Windowns. Make font loading more reliable. -- `BitMapBackend` isn't depdends on `image` crate now. Only the image encoding part relies on the `image` crate +- `BitMapBackend` isn't depends on `image` crate now. Only the image encoding part relies on the `image` crate - Refactored WASM demo use ES6 and `wasm-pack` (Thanks to @Tatrix) -- Label style for X axis and Y axis can be set seperately now using `x\_label\_style` and `y\_label\_style`. (Thanks to @zhiburt) +- Label style for X axis and Y axis can be set separately now using `x\_label\_style` and `y\_label\_style`. (Thanks to @zhiburt) ## Plotters 0.2.10 (2019-10-23) diff --git a/README.md b/README.md index fa451ddd..85c0a30e 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 some 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) @@ -158,15 +158,20 @@ To view the source code for each example, please click on the example image. ```sudo apt install pkg-config libfreetype6-dev libfontconfig1-dev``` +### Fedora Linux + + ```sudo dnf install pkgconf freetype-devel fontconfig-devel``` + ## Quick Start To use Plotters, you can simply add Plotters into your `Cargo.toml` ```toml [dependencies] -plotters = "0.3.1" +plotters = "0.3.3" ``` +Create the subdirectory `/plotters-doc-data` -And the following code draws a quadratic function. `src/main.rs`, +And the following code draws a quadratic function. `src/main.rs` writes the chart to `plotters-doc-data/0.png` ```rust use plotters::prelude::*; @@ -206,7 +211,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 +220,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.6", default-features = false, features = ["evcxr", "all_series", "all_elements"] } extern crate plotters; use plotters::prelude::*; @@ -256,7 +261,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 +271,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::*; @@ -324,7 +327,7 @@ fn main() -> Result<(), Box> { // Create a 800*600 bitmap and start drawing let mut backend = BitMapBackend::new("plotters-doc-data/1.png", (300, 200)); // And if we want SVG backend - // let backend = SVGBackend::new("output.svg", (800, 600)); + // let mut backend = SVGBackend::new("output.svg", (800, 600)); backend.draw_rect((50, 50), (200, 150), &RED, true)?; backend.present()?; Ok(()) @@ -335,10 +338,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 +363,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 +391,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 +434,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 +445,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,19 +492,19 @@ 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 Plotters now supports use features to control the backend dependencies. By default, `BitMapBackend` and `SVGBackend` are supported, -use `default_features = false` in the dependency description in `Cargo.toml` and you can cherry-pick the backend implementations. +use `default-features = false` in the dependency description in `Cargo.toml` and you can cherry-pick the backend implementations. - `svg` Enable the `SVGBackend` - `bitmap` Enable the `BitMapBackend` @@ -510,34 +513,63 @@ 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. -This behavior can also be turned off by setting `default_features = false`. +This behavior can also be turned off by setting `default-features = false`. ### List of Features This is the full list of features that is defined by `Plotters` crate. -Use `default_features = false` to disable those default enabled features, +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 +607,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. @@ -584,15 +616,15 @@ The following list is a complete list of features that can be opt in and out. Since Plotters 0.3, all drawing backends are independent crate from the main Plotters crate. Use the following link to find the backend code: - - [Bitmap Backend](https://github.com/plotters-rs/plotters-bitmap.git) - - [SVG Backend](https://github.com/plotters-rs/plotters-svg.git) + - [Bitmap Backend](./plotters-bitmap/) (current repository) + - [SVG Backend](./plotters-svg/) (current repository) - [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/RELEASE-NOTES.md b/RELEASE-NOTES.md index 91713c8f..060e922a 100644 --- a/RELEASE-NOTES.md +++ b/RELEASE-NOTES.md @@ -15,7 +15,7 @@ more and more backend is supported, those backend implementation cause a huge ma For example, when `cairo-rs` crate is updated, plotters should release a new version with updated `cairo-rs` dependency for our cairo backend. However, most of the users doesn't actually use this backend and pushing new version for updating cairo backend -seems to be annoying for most of the people. As more and more backend is added, the depdendency is out of control. +seems to be annoying for most of the people. As more and more backend is added, the dependency is out of control. ### Details @@ -54,13 +54,13 @@ Thus, if plotters is imported with default feature set, there would require no c should be make with your `Crates.toml`: ```toml -plotters = {version = "0.3", default_features = false, features = ["bitmap_backend", "svg_backend"]} # Instead of using feature "bitmap" and "svg" +plotters = {version = "0.3", default-features = false, features = ["bitmap_backend", "svg_backend"]} # Instead of using feature "bitmap" and "svg" ``` For non tier 1 backends, manmually import is required (Please note tier on backends can be imported in same way). For example: ```toml -plotters = {version = "0.3", default_features = false} # Instead of having features = ["cairo"] at this point +plotters = {version = "0.3", default-features = false} # Instead of having features = ["cairo"] at this point plotters-cairo = "0.3" # We should import the cairo backend in this way. ``` @@ -74,7 +74,7 @@ Plotters 0.3 ships with tons of improvement made in the coordinate abstraction a * `chrono::NaiveDate` and `chrono::NaiveDateTime` are now supported * Better abstraction of discrete coordinates -* Linspace coordinate, which can be used converting a continous coorindate into a discrete buckets +* Linspace coordinate, which can be used converting a continuous coorindate into a discrete buckets * Nested coordinate * Slices can now be used as cooradnite specification, which allows people define an axis of category. * 3D Coordinate is now supported 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..980be43e 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,19 +230,19 @@ $$../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 Plotters now supports use features to control the backend dependencies. By default, `BitMapBackend` and `SVGBackend` are supported, -use `default_features = false` in the dependency description in `Cargo.toml` and you can cherry-pick the backend implementations. +use `default-features = false` in the dependency description in `Cargo.toml` and you can cherry-pick the backend implementations. - `svg` Enable the `SVGBackend` - `bitmap` Enable the `BitMapBackend` @@ -253,34 +251,63 @@ 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. -This behavior can also be turned off by setting `default_features = false`. +This behavior can also be turned off by setting `default-features = false`. ### List of Features This is the full list of features that is defined by `Plotters` crate. -Use `default_features = false` to disable those default enabled features, +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..aad934c2 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.7" 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..0b35d1a3 100644 --- a/plotters-backend/src/lib.rs +++ b/plotters-backend/src/lib.rs @@ -3,7 +3,7 @@ Plotters project, please check the [main crate](https://crates.io/crates/plotters). This is the crate that used as the connector between Plotters and different backend crates. Since Plotters 0.3, all the backends has been - hosted as seperate crates for the usability and maintainability reasons. + hosted as separate crates for the usability and maintainability reasons. At the same time, Plotters is now supporting third-party backends and all the backends are now supports "plug-and-play": To use a external backend, just depends on both the Plotters main crate and the third-party backend crate. @@ -16,7 +16,7 @@ If the backend only implements [DrawingBackend::draw_pixel](trait.DrawingBackend.html#tymethod.draw_pixel), the default CPU rasterizer will be used to give your backend ability of drawing different shapes. For those backend that supports advanced drawing instructions, such as, GPU - acelerated shape drawing, all the provided trait method can be overriden from the specific backend code. + accelerated shape drawing, all the provided trait method can be overridden from the specific backend code. If your backend have text rendering ability, you may want to override the [DrawingBackend::estimate_text_size](trait.DrawingBackend.html#tymethod.estimate_text_size) to avoid wrong spacing, since the Plotters default text handling code may behaves differently from the backend in terms of text rendering. @@ -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| ---------> +-------------+ +-------------+ | +--------------+ ^ ^ | | | +------------------------------- + | @@ -48,12 +48,12 @@ - For dynamic drawing, frames are defined by invocation of `DrawingBackend::present`, everything prior the invocation should belongs to previous frame # Compatibility Note - Since Plotters v0.3, plotters use the "plug-and-play" schema to import backends, this requires both Plotters and the backend crates depdens on a + Since Plotters v0.3, plotters use the "plug-and-play" schema to import backends, this requires both Plotters and the backend crates depends on a same version of `plotters-backend` crate. This crate (`plotters-backend`) will enforce that any revision (means the last number in a version number) won't contains breaking change - both on the Plotters side and backend side. Plotters main crate is always importing the backend crate with version specification `plotters-backend = "^.*"`. - It's highly recommended that all the external crates follows the same rule to import `plotters-backend` depdendency, to avoid protential breaking + It's highly recommended that all the external crates follows the same rule to import `plotters-backend` dependency, to avoid potential breaking caused by `plotters-backend` crates gets a revision update. We also impose a versioning rule with `plotters` and some backends: @@ -233,8 +233,8 @@ pub trait DrawingBackend: Sized { .layout_box(text) .map_err(|e| DrawingErrorKind::FontError(Box::new(e)))?; 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 width = max_x - min_x; + let height = max_y - min_y; let dx = match style.anchor().h_pos { HPos::Left => 0, HPos::Right => -width, @@ -247,7 +247,7 @@ pub trait DrawingBackend: Sized { }; let trans = style.transform(); let (w, h) = self.get_size(); - match style.draw(text, (0, 0), |x, y, color| { + let drawing_result = style.draw(text, (0, 0), |x, y, color| { let (x, y) = trans.transform(x + dx - min_x, y + dy - min_y); let (x, y) = (pos.0 + x, pos.1 + y); if x >= 0 && x < w as i32 && y >= 0 && y < h as i32 { @@ -255,7 +255,8 @@ pub trait DrawingBackend: Sized { } else { Ok(()) } - }) { + }); + match drawing_result { Ok(drawing_result) => drawing_result, Err(font_error) => Err(DrawingErrorKind::FontError(Box::new(font_error))), } @@ -308,9 +309,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/circle.rs b/plotters-backend/src/rasterizer/circle.rs index 0584167a..fa7fc50d 100644 --- a/plotters-backend/src/rasterizer/circle.rs +++ b/plotters-backend/src/rasterizer/circle.rs @@ -53,9 +53,9 @@ fn draw_part_c< let (x0, x1) = ((-half_size).ceil() as i32, half_size.floor() as i32); for x in x0..x1 { - let outter_y0 = ((r_limit as f64) * (r_limit as f64) - x as f64 * x as f64).sqrt(); + let outer_y0 = ((r_limit as f64) * (r_limit as f64) - x as f64 * x as f64).sqrt(); let inner_y0 = r as f64 - 1.0; - let mut y1 = outter_y0.min(inner_y0); + let mut y1 = outer_y0.min(inner_y0); let y0 = ((r as f64) * (r as f64) - x as f64 * x as f64).sqrt(); if y0 > y1 { @@ -69,9 +69,9 @@ fn draw_part_c< } for x in x1 + 1..r { - let outter_y0 = ((r_limit as f64) * (r_limit as f64) - x as f64 * x as f64).sqrt(); + let outer_y0 = ((r_limit as f64) * (r_limit as f64) - x as f64 * x as f64).sqrt(); let inner_y0 = r as f64 - 1.0; - let y0 = outter_y0.min(inner_y0); + let y0 = outer_y0.min(inner_y0); let y1 = x as f64; if y1 < y0 { @@ -168,7 +168,6 @@ fn draw_annulus( radius.0 as f64 - a0, a1.floor(), |h, (f, t)| { - let h = h as i32; let f = f as i32; let t = t as i32; check_result!(b.draw_line( @@ -220,8 +219,8 @@ fn draw_annulus( )); let d_inner = ((radius.1 as f64) / (2f64).sqrt()) as i32; - let d_outter = (((radius.0 as f64) / (2f64).sqrt()) as i32).min(radius.1 as i32 - 1); - let d_outter_actually = (radius.1 as i32).min( + let d_outer = (((radius.0 as f64) / (2f64).sqrt()) as i32).min(radius.1 as i32 - 1); + let d_outer_actually = (radius.1 as i32).min( (radius.0 as f64 * radius.0 as f64 - radius.1 as f64 * radius.1 as f64 / 2.0) .sqrt() .ceil() as i32, @@ -229,43 +228,43 @@ fn draw_annulus( check_result!(b.draw_line( (center.0 - d_inner, center.1 - d_inner), - (center.0 - d_outter, center.1 - d_outter), + (center.0 - d_outer, center.1 - d_outer), &style.color() )); check_result!(b.draw_line( (center.0 + d_inner, center.1 - d_inner), - (center.0 + d_outter, center.1 - d_outter), + (center.0 + d_outer, center.1 - d_outer), &style.color() )); check_result!(b.draw_line( (center.0 - d_inner, center.1 + d_inner), - (center.0 - d_outter, center.1 + d_outter), + (center.0 - d_outer, center.1 + d_outer), &style.color() )); check_result!(b.draw_line( (center.0 + d_inner, center.1 + d_inner), - (center.0 + d_outter, center.1 + d_outter), + (center.0 + d_outer, center.1 + d_outer), &style.color() )); check_result!(b.draw_line( (center.0 - d_inner, center.1 + d_inner), - (center.0 - d_outter_actually, center.1 + d_inner), + (center.0 - d_outer_actually, center.1 + d_inner), &style.color() )); check_result!(b.draw_line( (center.0 + d_inner, center.1 - d_inner), - (center.0 + d_inner, center.1 - d_outter_actually), + (center.0 + d_inner, center.1 - d_outer_actually), &style.color() )); check_result!(b.draw_line( (center.0 + d_inner, center.1 + d_inner), - (center.0 + d_inner, center.1 + d_outter_actually), + (center.0 + d_inner, center.1 + d_outer_actually), &style.color() )); check_result!(b.draw_line( (center.0 + d_inner, center.1 + d_inner), - (center.0 + d_outter_actually, center.1 + d_inner), + (center.0 + d_outer_actually, center.1 + d_inner), &style.color() )); diff --git a/plotters-backend/src/rasterizer/line.rs b/plotters-backend/src/rasterizer/line.rs index 17836d9d..ae1ddd4c 100644 --- a/plotters-backend/src/rasterizer/line.rs +++ b/plotters-backend/src/rasterizer/line.rs @@ -110,7 +110,7 @@ pub fn draw_line( } if to.0 > batch_limit && y < f64::from(to.1) { - let x = batch_limit as i32 + 1; + let x = batch_limit + 1; if 1.0 + y.floor() - y > 1e-5 { check_result!(put_pixel((x, y as i32), 1.0 + y.floor() - y)); } 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..004461c2 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 f64::EPSILON { - let u = (c0 * b1 - c1 * b0) / (a0 * b1 - a1 * b0); - - x = a_p.0 + u * a_t.0; - y = a_p.1 + u * a_t.1; - } + // Since the points are not collinear, the determinant is not 0, and we can get a intersection point. + let u = (c0 * b1 - c1 * b0) / (a0 * b1 - a1 * b0); + let x = a_p.0 + u * a_t.0; + let y = a_p.1 + u * a_t.1; let cross_product = a_t.0 * b_t.1 - a_t.1 * b_t.0; if (cross_product < 0.0 && d < 0.0) || (cross_product > 0.0 && d > 0.0) { - // Then we are at the outter side of the angle, so we need to consider a cap. + // Then we are at the outer side of the angle, so we need to consider a cap. let dist_square = (x - triple[1].0 as f64).powi(2) + (y - triple[1].1 as f64).powi(2); // If the point is too far away from the line, we need to cap it. if dist_square > d * d * 16.0 { @@ -149,3 +143,30 @@ pub fn polygonize(vertices: &[BackendCoord], stroke_width: u32) -> Vec Option { - self.get_slave_pos().partial_cmp(&other.get_slave_pos()) + Some(self.cmp(other)) } } diff --git a/plotters-backend/src/text.rs b/plotters-backend/src/text.rs index 16e2c665..98fe4bef 100644 --- a/plotters-backend/src/text.rs +++ b/plotters-backend/src/text.rs @@ -60,9 +60,10 @@ impl<'a> 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, - } - } } } @@ -201,8 +187,8 @@ impl<'a> From<&'a str> for FontStyle { /// text drawing, those font information provides instructions about how the text should be /// rendered: color, size, slant, anchor, font, etc. /// -/// This trait decouples the detailed implementaiton about the font and the backend code which -/// wants to perfome some operation on the font. +/// This trait decouples the detailed implementation about the font and the backend code which +/// wants to perform some operation on the font. /// pub trait BackendTextStyle { /// The error type of this text style implementation diff --git a/plotters-bitmap/Cargo.toml b/plotters-bitmap/Cargo.toml index 6a48bc08..c721da63 100644 --- a/plotters-bitmap/Cargo.toml +++ b/plotters-bitmap/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "plotters-bitmap" -version = "0.3.3" +version = "0.3.7" authors = ["Hao Hou "] edition = "2018" license = "MIT" @@ -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.6" path = "../plotters-backend" [target.'cfg(not(target_arch = "wasm32"))'.dependencies.image] @@ -29,12 +30,12 @@ image_encoder = ["image"] gif_backend = ["gif", "image_encoder"] [dev-dependencies.plotters] -default_features = false +default-features = false features = ["ttf", "line_series", "bitmap_backend"] path = "../plotters" [dev-dependencies] -criterion = "0.3.6" +criterion = "0.5.1" 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..5edd3cda 100644 --- a/plotters-bitmap/src/bitmap.rs +++ b/plotters-bitmap/src/bitmap.rs @@ -28,7 +28,7 @@ use target::{Buffer, Target}; /// `BitMapBackend`, not just `drop` it or allow it to go out of scope. /// /// If the `BitMapBackend` is just dropped, it will make a best effort attempt to write the -/// generated charts to the output file, but any errors that occcur (such as inability to +/// generated charts to the output file, but any errors that occur (such as inability to /// create the output file) will be silently ignored. pub struct BitMapBackend<'a, P: PixelFormat = RGBPixel> { /// The path to the image @@ -91,11 +91,11 @@ 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 - /// uses RGB pixel format and maniuplates the in-memory framebuffer. + /// uses RGB pixel format and manipulates the in-memory framebuffer. /// For more pixel format option, use `with_buffer_and_format` instead. /// /// - `buf`: The buffer to operate @@ -141,7 +141,7 @@ impl<'a, P: PixelFormat> BitMapBackend<'a, P> { /// multi-threading rendering. /// /// - `area_size`: The size of the area - /// - **returns**: The splitted backends that can be rendered in parallel + /// - **returns**: The split backends that can be rendered in parallel pub fn split(&mut self, area_size: &[u32]) -> Vec> { let (w, h) = self.get_size(); let buf = self.get_raw_pixel_buffer(); diff --git a/plotters-bitmap/src/bitmap/target.rs b/plotters-bitmap/src/bitmap/target.rs index b4dc210d..5384f4d3 100644 --- a/plotters-bitmap/src/bitmap/target.rs +++ b/plotters-bitmap/src/bitmap/target.rs @@ -24,7 +24,7 @@ impl<'a> Buffer<'a> { match self { #[cfg(all(not(target_arch = "wasm32"), feature = "image"))] Buffer::Owned(buf) => &mut buf[..], - Buffer::Borrowed(buf) => *buf, + Buffer::Borrowed(buf) => buf, } } } diff --git a/plotters-bitmap/src/bitmap_pixel/bgrx.rs b/plotters-bitmap/src/bitmap_pixel/bgrx.rs index 16bcd25e..fe97f4da 100644 --- a/plotters-bitmap/src/bitmap_pixel/bgrx.rs +++ b/plotters-bitmap/src/bitmap_pixel/bgrx.rs @@ -36,7 +36,7 @@ impl PixelFormat for BGRXPixel { a: f64, ) { let (w, h) = target.get_size(); - let a = a.min(1.0).max(0.0); + let a = a.clamp(0.0, 1.0); if a == 0.0 { return; } @@ -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..1200cc09 100644 --- a/plotters-bitmap/src/bitmap_pixel/rgb.rs +++ b/plotters-bitmap/src/bitmap_pixel/rgb.rs @@ -40,7 +40,7 @@ impl PixelFormat for RGBPixel { a: f64, ) { let (w, h) = target.get_size(); - let a = a.min(1.0).max(0.0); + let a = a.clamp(0.0, 1.0); if a == 0.0 { return; } @@ -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-bitmap/src/error.rs b/plotters-bitmap/src/error.rs index 4fa10205..10a668df 100644 --- a/plotters-bitmap/src/error.rs +++ b/plotters-bitmap/src/error.rs @@ -6,7 +6,7 @@ use image::ImageError; pub enum BitMapBackendError { /// The buffer provided is invalid, for example, wrong pixel buffer size InvalidBuffer, - /// Some IO error occurs while the bitmap maniuplation + /// Some IO error occurs while the bitmap manipulation IOError(std::io::Error), #[cfg(all(feature = "gif", not(target_arch = "wasm32"), feature = "image"))] GifEncodingError(gif::EncodingError), diff --git a/plotters-svg/Cargo.toml b/plotters-svg/Cargo.toml index 30cd37e6..b83a965e 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.7" 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.6" path = "../plotters-backend" [dependencies.image] @@ -25,6 +26,6 @@ debug = [] bitmap_encoder = ["image"] [dev-dependencies.plotters] -default_features = false +default-features = false features = ["ttf"] path = "../plotters" 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..e24623d7 100644 --- a/plotters-svg/src/svg.rs +++ b/plotters-svg/src/svg.rs @@ -8,30 +8,21 @@ 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; - return format!("#{:02X}{:02X}{:02X}", r, g, b); -} - -fn make_svg_opacity(color: BackendColor) -> String { - return format!("{}", color.alpha); +struct Rgb(u8, u8, u8); +fn make_svg_color(color: BackendColor) -> Rgb { + Rgb(color.rgb.0, color.rgb.1, color.rgb.2) } enum Target<'a> { File(String, &'a Path), Buffer(&'a mut String), - // TODO: At this point we won't make the breaking change - // so the u8 buffer is still supported. But in 0.3, we definitely - // should get rid of this. - #[cfg(feature = "deprecated_items")] - U8Buffer(String, &'a mut Vec), } impl Target<'_> { @@ -39,12 +30,11 @@ impl Target<'_> { match self { Target::File(ref mut buf, _) => buf, Target::Buffer(buf) => buf, - #[cfg(feature = "deprecated_items")] - Target::U8Buffer(ref mut buf, _) => buf, } } } +#[derive(Clone)] enum SVGTag { Svg, Circle, @@ -80,36 +70,157 @@ pub struct SVGBackend<'a> { saved: bool, } -impl<'a> SVGBackend<'a> { - fn escape_and_push(buf: &mut String, value: &str) { - value.chars().for_each(|c| match c { +trait FormatEscaped { + fn format_escaped(buf: &mut String, s: Self); +} +macro_rules! impl_format_escaped_tuple { + ($($idx:tt $t:tt),+) => { + impl<$($t,)+> FormatEscaped for ($($t,)+) + where + $($t: FormatEscaped,)+ + { + fn format_escaped(buf: &mut String, tup: Self) { + $( + FormatEscaped::format_escaped(buf, tup.$idx); + )+ + } + } + }; +} +impl_format_escaped_tuple!(0 A); +impl_format_escaped_tuple!(0 A, 1 B); +impl_format_escaped_tuple!(0 A, 1 B, 2 C); +impl_format_escaped_tuple!(0 A, 1 B, 2 C, 3 D); +impl_format_escaped_tuple!(0 A, 1 B, 2 C, 3 D, 4 E); +impl_format_escaped_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F); +impl_format_escaped_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G); + +macro_rules! impl_format_escaped_plain { + ($($t:ty),*) => { + $( + impl FormatEscaped for $t { + fn format_escaped(buf: &mut String, s: Self) { + let _ = write!(buf, "{}", s); + } + } + )* + }; +} + +impl_format_escaped_plain!(u32, i32, f32, f64); +impl FormatEscaped for &str { + fn format_escaped(buf: &mut String, s: &str) { + for c in s.chars() { + FormatEscaped::format_escaped(buf, c); + } + } +} + +impl FormatEscaped for Rgb { + fn format_escaped(buf: &mut String, Rgb(r, g, b): Rgb) { + let _ = write!(buf, "#{:02X}{:02X}{:02X}", r, g, b); + } +} + +impl FormatEscaped for Option { + fn format_escaped(buf: &mut String, opt: Option) { + match opt { + None => { + FormatEscaped::format_escaped(buf, "none"); + } + Some(x) => { + FormatEscaped::format_escaped(buf, x); + } + } + } +} + +impl FormatEscaped for char { + fn format_escaped(buf: &mut String, c: char) { + match c { '<' => buf.push_str("<"), '>' => buf.push_str(">"), '&' => buf.push_str("&"), '"' => buf.push_str("""), '\'' => buf.push_str("'"), other => buf.push(other), - }); + }; + } +} + +struct FormatEscapedIter(I); +impl> FormatEscaped for FormatEscapedIter { + fn format_escaped(buf: &mut String, iter: FormatEscapedIter) { + let iter = iter.0.into_iter(); + for item in iter { + FormatEscaped::format_escaped(buf, item); + } } - fn open_tag(&mut self, tag: SVGTag, attr: &[(&str, &str)], close: bool) { - let buf = self.target.get_mut(); +} + +enum Value {} +enum Init {} +struct AttrWriter<'a, State> { + buf: &'a mut String, + tag: SVGTag, + tag_stack: &'a mut Vec, + state: std::marker::PhantomData, +} + +/// Used for opening a tag and then optionally writing some attributes. The expected workflow is +/// to call [open_tag](AttrWriter::open_tag), then zero or more times calling +/// [write_key](AttrWriter::write_key) followed optionally by `[write_value](AttrWriter::write_value)` +/// and finally calling one of [close](AttrWriter::close) (to close a self-closing tag) +/// or [finish_without_closing](AttrWriter::finish_without_closing) (to schedule writing +// writing the closing tag for later). +impl<'a> AttrWriter<'a, Init> { + fn open_tag(buf: &'a mut String, tag: SVGTag, tag_stack: &'a mut Vec) -> Self { buf.push('<'); buf.push_str(tag.to_tag_name()); - for (key, value) in attr { - buf.push(' '); - buf.push_str(key); - buf.push_str("=\""); - Self::escape_and_push(buf, value); - buf.push('\"'); - } - if close { - buf.push_str("/>\n"); - } else { - self.tag_stack.push(tag); - buf.push_str(">\n"); + AttrWriter { + buf, + tag, + tag_stack, + state: Default::default(), + } + } + + fn write_key<'s>(&'s mut self, key: &str) -> AttrWriter<'s, Value> { + self.buf.push(' '); + self.buf.push_str(key); + AttrWriter { + buf: self.buf, + tag: self.tag.clone(), + tag_stack: self.tag_stack, + state: Default::default(), } } + fn close(self) { + self.buf.push_str("/>\n"); + } + + fn finish_without_closing(self) { + self.tag_stack.push(self.tag); + self.buf.push_str(">\n"); + } +} + +impl<'a> AttrWriter<'a, Value> { + fn write_value(self, value: impl FormatEscaped) { + self.buf.push_str("=\""); + FormatEscaped::format_escaped(self.buf, value); + self.buf.push('"'); + } +} + +impl<'a> SVGBackend<'a> { + fn escape_and_push(buf: &mut String, value: &str) { + value + .chars() + .for_each(|c| FormatEscaped::format_escaped(buf, c)); + } + fn close_tag(&mut self) -> bool { if let Some(tag) = self.tag_stack.pop() { let buf = self.target.get_mut(); @@ -121,17 +232,22 @@ impl<'a> SVGBackend<'a> { false } + /// Opens a tag and provides facilities for writing attrs and closing the tag + fn open_tag(&mut self, tag: SVGTag) -> AttrWriter<'_, Init> { + AttrWriter::open_tag(self.target.get_mut(), tag, &mut self.tag_stack) + } + fn init_svg_file(&mut self, size: (u32, u32)) { - self.open_tag( - SVGTag::Svg, - &[ - ("width", &format!("{}", size.0)), - ("height", &format!("{}", size.1)), - ("viewBox", &format!("0 0 {} {}", size.0, size.1)), - ("xmlns", "http://www.w3.org/2000/svg"), - ], - false, - ); + let mut attrwriter = self.open_tag(SVGTag::Svg); + attrwriter.write_key("width").write_value(size.0); + attrwriter.write_key("height").write_value(size.1); + attrwriter + .write_key("viewBox") + .write_value(("0 0 ", size.0, ' ', size.1)); + attrwriter + .write_key("xmlns") + .write_value("http://www.w3.org/2000/svg"); + attrwriter.finish_without_closing(); } /// Create a new SVG drawing backend @@ -147,24 +263,6 @@ impl<'a> SVGBackend<'a> { ret } - /// Create a new SVG drawing backend and store the document into a u8 vector - #[cfg(feature = "deprecated_items")] - #[deprecated( - note = "This will be replaced by `with_string`, consider use `with_string` to avoid breaking change in the future" - )] - pub fn with_buffer(buf: &'a mut Vec, size: (u32, u32)) -> Self { - let mut ret = Self { - target: Target::U8Buffer(String::default(), buf), - size, - tag_stack: vec![], - saved: false, - }; - - ret.init_svg_file(size); - - ret - } - /// Create a new SVG drawing backend and store the document into a String buffer pub fn with_string(buf: &'a mut String, size: (u32, u32)) -> Self { let mut ret = Self { @@ -203,11 +301,6 @@ impl<'a> DrawingBackend for SVGBackend<'a> { .map_err(DrawingErrorKind::DrawingError)?; } Target::Buffer(_) => {} - #[cfg(feature = "deprecated_items")] - Target::U8Buffer(ref actual, ref mut target) => { - target.clear(); - target.extend_from_slice(actual.as_bytes()); - } } self.saved = true; } @@ -222,19 +315,17 @@ impl<'a> DrawingBackend for SVGBackend<'a> { if color.alpha == 0.0 { return Ok(()); } - self.open_tag( - SVGTag::Rectangle, - &[ - ("x", &format!("{}", point.0)), - ("y", &format!("{}", point.1)), - ("width", "1"), - ("height", "1"), - ("stroke", "none"), - ("opacity", &make_svg_opacity(color)), - ("fill", &make_svg_color(color)), - ], - true, - ); + let mut attrwriter = self.open_tag(SVGTag::Rectangle); + attrwriter.write_key("x").write_value(point.0); + attrwriter.write_key("y").write_value(point.1); + attrwriter.write_key("width").write_value("1"); + attrwriter.write_key("height").write_value("1"); + attrwriter.write_key("stroke").write_value("none"); + attrwriter.write_key("opacity").write_value(color.alpha); + attrwriter + .write_key("fill") + .write_value(make_svg_color(color)); + attrwriter.close(); Ok(()) } @@ -247,19 +338,21 @@ impl<'a> DrawingBackend for SVGBackend<'a> { if style.color().alpha == 0.0 { return Ok(()); } - self.open_tag( - SVGTag::Line, - &[ - ("opacity", &make_svg_opacity(style.color())), - ("stroke", &make_svg_color(style.color())), - ("stroke-width", &format!("{}", style.stroke_width())), - ("x1", &format!("{}", from.0)), - ("y1", &format!("{}", from.1)), - ("x2", &format!("{}", to.0)), - ("y2", &format!("{}", to.1)), - ], - true, - ); + let mut attrwriter = self.open_tag(SVGTag::Line); + attrwriter + .write_key("opacity") + .write_value(style.color().alpha); + attrwriter + .write_key("stroke") + .write_value(make_svg_color(style.color())); + attrwriter + .write_key("stroke-width") + .write_value(style.stroke_width()); + attrwriter.write_key("x1").write_value(from.0); + attrwriter.write_key("y1").write_value(from.1); + attrwriter.write_key("x2").write_value(to.0); + attrwriter.write_key("y2").write_value(to.1); + attrwriter.close(); Ok(()) } @@ -274,26 +367,28 @@ impl<'a> DrawingBackend for SVGBackend<'a> { return Ok(()); } + let color = make_svg_color(style.color()); let (fill, stroke) = if !fill { - ("none".to_string(), make_svg_color(style.color())) + (None, Some(color)) } else { - (make_svg_color(style.color()), "none".to_string()) + (Some(color), None) }; - self.open_tag( - SVGTag::Rectangle, - &[ - ("x", &format!("{}", upper_left.0)), - ("y", &format!("{}", upper_left.1)), - ("width", &format!("{}", bottom_right.0 - upper_left.0)), - ("height", &format!("{}", bottom_right.1 - upper_left.1)), - ("opacity", &make_svg_opacity(style.color())), - ("fill", &fill), - ("stroke", &stroke), - ], - true, - ); - + let mut attrwriter = self.open_tag(SVGTag::Rectangle); + attrwriter.write_key("x").write_value(upper_left.0); + attrwriter.write_key("y").write_value(upper_left.1); + attrwriter + .write_key("width") + .write_value(bottom_right.0 - upper_left.0); + attrwriter + .write_key("height") + .write_value(bottom_right.1 - upper_left.1); + attrwriter + .write_key("opacity") + .write_value(style.color().alpha); + attrwriter.write_key("fill").write_value(fill); + attrwriter.write_key("stroke").write_value(stroke); + attrwriter.close(); Ok(()) } @@ -305,23 +400,23 @@ impl<'a> DrawingBackend for SVGBackend<'a> { if style.color().alpha == 0.0 { return Ok(()); } - self.open_tag( - SVGTag::Polyline, - &[ - ("fill", "none"), - ("opacity", &make_svg_opacity(style.color())), - ("stroke", &make_svg_color(style.color())), - ("stroke-width", &format!("{}", style.stroke_width())), - ( - "points", - &path.into_iter().fold(String::new(), |mut s, (x, y)| { - write!(s, "{},{} ", x, y).ok(); - s - }), - ), - ], - true, - ); + let mut attrwriter = self.open_tag(SVGTag::Polyline); + attrwriter.write_key("fill").write_value("none"); + attrwriter + .write_key("opacity") + .write_value(style.color().alpha); + attrwriter + .write_key("stroke") + .write_value(make_svg_color(style.color())); + attrwriter + .write_key("stroke-width") + .write_value(style.stroke_width()); + attrwriter + .write_key("points") + .write_value(FormatEscapedIter( + path.into_iter().map(|c| (c.0, ',', c.1, ' ')), + )); + attrwriter.close(); Ok(()) } @@ -333,21 +428,20 @@ impl<'a> DrawingBackend for SVGBackend<'a> { if style.color().alpha == 0.0 { return Ok(()); } - self.open_tag( - SVGTag::Polygon, - &[ - ("opacity", &make_svg_opacity(style.color())), - ("fill", &make_svg_color(style.color())), - ( - "points", - &path.into_iter().fold(String::new(), |mut s, (x, y)| { - write!(s, "{},{} ", x, y).ok(); - s - }), - ), - ], - true, - ); + let mut attrwriter = self.open_tag(SVGTag::Polygon); + attrwriter + .write_key("opacity") + .write_value(style.color().alpha); + attrwriter + .write_key("fill") + .write_value(make_svg_color(style.color())); + attrwriter + .write_key("points") + .write_value(FormatEscapedIter( + path.into_iter().map(|c| (c.0, ',', c.1, ' ')), + )); + attrwriter.close(); + Ok(()) } @@ -361,24 +455,25 @@ impl<'a> DrawingBackend for SVGBackend<'a> { if style.color().alpha == 0.0 { return Ok(()); } + let color = make_svg_color(style.color()); let (stroke, fill) = if !fill { - (make_svg_color(style.color()), "none".to_string()) + (Some(color), None) } else { - ("none".to_string(), make_svg_color(style.color())) + (None, Some(color)) }; - self.open_tag( - SVGTag::Circle, - &[ - ("cx", &format!("{}", center.0)), - ("cy", &format!("{}", center.1)), - ("r", &format!("{}", radius)), - ("opacity", &make_svg_opacity(style.color())), - ("fill", &fill), - ("stroke", &stroke), - ("stroke-width", &format!("{}", style.stroke_width())), - ], - true, - ); + let mut attrwriter = self.open_tag(SVGTag::Circle); + attrwriter.write_key("cx").write_value(center.0); + attrwriter.write_key("cy").write_value(center.1); + attrwriter.write_key("r").write_value(radius); + attrwriter + .write_key("opacity") + .write_value(style.color().alpha); + attrwriter.write_key("fill").write_value(fill); + attrwriter.write_key("stroke").write_value(stroke); + attrwriter + .write_key("stroke-width") + .write_value(style.stroke_width()); + attrwriter.close(); Ok(()) } @@ -431,46 +526,54 @@ impl<'a> DrawingBackend for SVGBackend<'a> { .unwrap(); } - let mut attrs = vec![ - ("x", format!("{}", x0)), - ("y", format!("{}", y0)), - ("dy", dy.to_owned()), - ("text-anchor", text_anchor.to_string()), - ("font-family", style.family().as_str().to_string()), - ("font-size", format!("{}", style.size() / 1.24)), - ("opacity", make_svg_opacity(color)), - ("fill", make_svg_color(color)), - ]; + let mut attrwriter = self.open_tag(SVGTag::Text); + attrwriter.write_key("x").write_value(x0); + attrwriter.write_key("y").write_value(y0); + attrwriter.write_key("dy").write_value(dy); + attrwriter.write_key("text-anchor").write_value(text_anchor); + attrwriter + .write_key("font-family") + .write_value(style.family().as_str()); + attrwriter + .write_key("font-size") + .write_value(style.size() / 1.24); + attrwriter.write_key("opacity").write_value(color.alpha); + attrwriter + .write_key("fill") + .write_value(make_svg_color(color)); match style.style() { FontStyle::Normal => {} - FontStyle::Bold => attrs.push(("font-weight", "bold".to_string())), - other_style => attrs.push(("font-style", other_style.as_str().to_string())), + FontStyle::Bold => { + attrwriter.write_key("font-weight").write_value("bold"); + } + other_style => { + attrwriter + .write_key("font-style") + .write_value(other_style.as_str()); + } }; let trans = style.transform(); match trans { FontTransform::Rotate90 => { - attrs.push(("transform", format!("rotate(90, {}, {})", x0, y0))) + attrwriter + .write_key("transform") + .write_value(("rotate(90, ", x0, ", ", y0, ')')); } FontTransform::Rotate180 => { - attrs.push(("transform", format!("rotate(180, {}, {})", x0, y0))); + attrwriter + .write_key("transform") + .write_value(("rotate(180, ", x0, ", ", y0, ')')); } FontTransform::Rotate270 => { - attrs.push(("transform", format!("rotate(270, {}, {})", x0, y0))); + attrwriter + .write_key("transform") + .write_value(("rotate(270, ", x0, ", ", y0, ')')); } _ => {} } - - self.open_tag( - SVGTag::Text, - attrs - .iter() - .map(|(a, b)| (*a, b.as_ref())) - .collect::>() - .as_ref(), - false, - ); + attrwriter.finish_without_closing(); Self::escape_and_push(self.target.get_mut(), text); self.target.get_mut().push('\n'); @@ -481,11 +584,11 @@ impl<'a> DrawingBackend for SVGBackend<'a> { } #[cfg(all(not(target_arch = "wasm32"), feature = "image"))] - fn blit_bitmap<'b>( + fn blit_bitmap( &mut self, pos: BackendCoord, (w, h): (u32, u32), - src: &'b [u8], + src: &[u8], ) -> Result<(), DrawingErrorKind> { use image::codecs::png::PngEncoder; use image::ImageEncoder; @@ -508,9 +611,7 @@ impl<'a> DrawingBackend for SVGBackend<'a> { } let padding = (3 - data.len() % 3) % 3; - for _ in 0..padding { - data.push(0); - } + data.resize(data.len() + padding, 0); let mut rem_bits = 0; let mut rem_num = 0; @@ -551,17 +652,13 @@ impl<'a> DrawingBackend for SVGBackend<'a> { buf.push('='); } - self.open_tag( - SVGTag::Image, - &[ - ("x", &format!("{}", pos.0)), - ("y", &format!("{}", pos.1)), - ("width", &format!("{}", w)), - ("height", &format!("{}", h)), - ("href", buf.as_str()), - ], - true, - ); + let mut attrwriter = self.open_tag(SVGTag::Image); + attrwriter.write_key("x").write_value(pos.0); + attrwriter.write_key("y").write_value(pos.1); + attrwriter.write_key("width").write_value(w); + attrwriter.write_key("height").write_value(h); + attrwriter.write_key("href").write_value(buf.as_str()); + attrwriter.close(); Ok(()) } diff --git a/plotters/Cargo.toml b/plotters/Cargo.toml index 91f9025d..cb06eec8 100644 --- a/plotters/Cargo.toml +++ b/plotters/Cargo.toml @@ -1,39 +1,49 @@ [package] name = "plotters" -version = "0.3.4" +version = "0.3.7" authors = ["Hao Hou "] edition = "2018" license = "MIT" +msrv = "1.56" description = "A Rust drawing library focus on data plotting for both WASM and native applications" 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"] +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(doc_cfg)'] } +deprecated = { level = "allow" } + [dependencies] num-traits = "0.2.14" -chrono = { version = "0.4.20", optional = true } +chrono = { version = "0.4.32", optional = true } [dependencies.plotters-backend] +version = "0.3.6" path = "../plotters-backend" [dependencies.plotters-bitmap] -default_features = false +version = "0.3.6" +default-features = false optional = true path = "../plotters-bitmap" [dependencies.plotters-svg] -version = "^0.3" +version = "0.3.6" 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.20.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 } +font-kit = { version = "0.14.2", 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" @@ -42,10 +52,10 @@ default-features = false features = ["jpeg", "png", "bmp"] [target.'cfg(all(target_arch = "wasm32", not(target_os = "wasi")))'.dependencies.wasm-bindgen] -version = "0.2.62" +version = "0.2.89" [target.'cfg(all(target_arch = "wasm32", not(target_os = "wasi")))'.dependencies.web-sys] -version = "0.3.51" +version = "0.3.66" features = [ "Document", "DomRect", @@ -65,19 +75,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"] +all_series = ["area_series", "line_series", "point_series", "surface_series", "histogram"] +all_elements = ["errorbar", "candlestick", "boxplot"] # 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 +109,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 +119,7 @@ deprecated_items = [] # Keep some of the deprecated items for backward compatibi [dev-dependencies] itertools = "0.10.0" -criterion = "0.3.6" +criterion = "0.5.1" rayon = "1.5.1" serde_json = "1.0.82" serde = "1.0.139" @@ -117,9 +131,14 @@ rand_distr = "0.4.0" rand_xorshift = "0.3.0" [target.'cfg(all(target_arch = "wasm32", not(target_os = "wasi")))'.dev-dependencies] -wasm-bindgen-test = "0.3.24" +wasm-bindgen-test = "0.3.39" [[bench]] 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/clippy.toml b/plotters/clippy.toml deleted file mode 100644 index 17852009..00000000 --- a/plotters/clippy.toml +++ /dev/null @@ -1 +0,0 @@ -msrv = "1.56" \ No newline at end of file diff --git a/plotters/examples/3d-plot.rs b/plotters/examples/3d-plot.rs index af40cc29..7bfc6c3e 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", ("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/README.md b/plotters/examples/README.md index b6dd1666..3149df7c 100644 --- a/plotters/examples/README.md +++ b/plotters/examples/README.md @@ -4,7 +4,7 @@ To run any example, from within the repo, run `cargo run --example ` where `` is the name of the file without the `.rs` extension. -All the examples assumes the directory [plotters-doc-data](https://github.com/38/plotters-doc-data) exists, otherwise those example crashs. +All the examples assumes the directory [plotters-doc-data](https://github.com/38/plotters-doc-data) exists, otherwise those example crashes. The output of these example files are used to generate the [plotters-doc-data](https://github.com/38/plotters-doc-data) repo that populates the sample images in the main README. We also rely on the output of examples to detect potential layout changes. 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..814fb5f2 100644 --- a/plotters/examples/console.rs +++ b/plotters/examples/console.rs @@ -183,7 +183,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..09ce561c 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(); @@ -11,7 +11,7 @@ fn main() -> Result<(), Box> { .margin(5) .top_x_label_area_size(40) .y_label_area_size(40) - .build_cartesian_2d(0i32..15i32, 15i32..0i32)?; + .build_cartesian_2d(0i32..15i32, 0i32..15i32)?; chart .configure_mesh() @@ -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/builder.rs b/plotters/src/chart/builder.rs index cf804c6e..41a4309b 100644 --- a/plotters/src/chart/builder.rs +++ b/plotters/src/chart/builder.rs @@ -194,7 +194,7 @@ impl<'a, 'b, DB: DrawingBackend> ChartBuilder<'a, 'b, DB> { Sets the size of the X label area at the bottom of the chart. - `size`: The desired size of the X label area in backend units (pixels). - If set to 0, the X label area is removed. + If set to 0, the X label area is removed. See [`ChartBuilder::on()`] for more information and examples. */ @@ -206,7 +206,7 @@ impl<'a, 'b, DB: DrawingBackend> ChartBuilder<'a, 'b, DB> { Sets the size of the Y label area to the left of the chart. - `size`: The desired size of the Y label area in backend units (pixels). - If set to 0, the Y label area is removed. + If set to 0, the Y label area is removed. See [`ChartBuilder::on()`] for more information and examples. */ @@ -218,7 +218,7 @@ impl<'a, 'b, DB: DrawingBackend> ChartBuilder<'a, 'b, DB> { Sets the size of the X label area at the top of the chart. - `size`: The desired size of the top X label area in backend units (pixels). - If set to 0, the top X label area is removed. + If set to 0, the top X label area is removed. See [`ChartBuilder::on()`] for more information and examples. */ @@ -230,7 +230,7 @@ impl<'a, 'b, DB: DrawingBackend> ChartBuilder<'a, 'b, DB> { Sets the size of the Y label area to the right of the chart. - `size`: The desired size of the Y label area in backend units (pixels). - If set to 0, the Y label area to the right is removed. + If set to 0, the Y label area to the right is removed. See [`ChartBuilder::on()`] for more information and examples. */ @@ -243,7 +243,7 @@ impl<'a, 'b, DB: DrawingBackend> ChartBuilder<'a, 'b, DB> { - `pos`: The position of the desired label area to adjust - `size`: The desired size of the label area in backend units (pixels). - If set to 0, the label area is removed. + If set to 0, the label area is removed. See [`ChartBuilder::on()`] for more information and examples. */ @@ -285,12 +285,12 @@ impl<'a, 'b, DB: DrawingBackend> ChartBuilder<'a, 'b, DB> { #[deprecated( note = "`build_ranged` has been renamed to `build_cartesian_2d` and is to be removed in the future." )] - pub fn build_ranged( + pub fn build_ranged<'c, X: AsRangedCoord, Y: AsRangedCoord>( &mut self, x_spec: X, y_spec: Y, ) -> Result< - ChartContext<'a, DB, Cartesian2d>, + ChartContext<'c, DB, Cartesian2d>, DrawingAreaErrorKind, > { self.build_cartesian_2d(x_spec, y_spec) @@ -306,12 +306,12 @@ impl<'a, 'b, DB: DrawingBackend> ChartBuilder<'a, 'b, DB> { See [`ChartBuilder::on()`] and [`ChartContext::configure_mesh()`] for more information and examples. */ #[allow(clippy::type_complexity)] - pub fn build_cartesian_2d( + pub fn build_cartesian_2d<'c, X: AsRangedCoord, Y: AsRangedCoord>( &mut self, x_spec: X, y_spec: Y, ) -> Result< - ChartContext<'a, DB, Cartesian2d>, + ChartContext<'c, DB, Cartesian2d>, DrawingAreaErrorKind, > { let mut label_areas = [None, None, None, None]; @@ -450,13 +450,13 @@ impl<'a, 'b, DB: DrawingBackend> ChartBuilder<'a, 'b, DB> { See [`ChartBuilder::on()`] and [`ChartContext::configure_axes()`] for more information and examples. */ #[allow(clippy::type_complexity)] - pub fn build_cartesian_3d( + pub fn build_cartesian_3d<'c, X: AsRangedCoord, Y: AsRangedCoord, Z: AsRangedCoord>( &mut self, x_spec: X, y_spec: Y, z_spec: Z, ) -> Result< - ChartContext<'a, DB, Cartesian3d>, + ChartContext<'c, DB, Cartesian3d>, DrawingAreaErrorKind, > { let mut drawing_area = DrawingArea::clone(self.root_area); @@ -565,4 +565,27 @@ mod test { chart.caption("This is a test case", ("serif", 10)); assert_eq!(chart.title.as_ref().unwrap().1.font.get_name(), "serif"); } + + #[test] + fn test_zero_limit_with_log_scale() { + let drawing_area = create_mocked_drawing_area(640, 480, |_| {}); + + let mut chart = ChartBuilder::on(&drawing_area) + .build_cartesian_2d(0f32..10f32, (1e-6f32..1f32).log_scale()) + .unwrap(); + + let data = vec![ + (2f32, 1e-4f32), + (4f32, 1e-3f32), + (6f32, 1e-2f32), + (8f32, 1e-1f32), + ]; + + chart + .draw_series( + data.iter() + .map(|&(x, y)| Rectangle::new([(x - 0.5, 0.0), (x + 0.5, y)], RED.filled())), + ) + .unwrap(); + } } 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..17452737 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) diff --git a/plotters/src/chart/context/cartesian3d/mod.rs b/plotters/src/chart/context/cartesian3d/mod.rs index ff28adf4..43d74f38 100644 --- a/plotters/src/chart/context/cartesian3d/mod.rs +++ b/plotters/src/chart/context/cartesian3d/mod.rs @@ -106,9 +106,9 @@ where /// Override the 3D projection matrix. This function allows to override the default projection /// matrix. /// - `pf`: A function that takes the default projection matrix configuration and returns the - /// projection matrix. This function will allow you to adjust the pitch, yaw angle and the - /// centeral point of the projection, etc. You can also build a projection matrix which is not - /// relies on the default configuration as well. + /// projection matrix. This function will allow you to adjust the pitch, yaw angle and the + /// centeral point of the projection, etc. You can also build a projection matrix which is not + /// relies on the default configuration as well. pub fn with_projection ProjectionMatrix>( &mut self, pf: P, diff --git a/plotters/src/chart/dual_coord.rs b/plotters/src/chart/dual_coord.rs index d5960e03..048bea02 100644 --- a/plotters/src/chart/dual_coord.rs +++ b/plotters/src/chart/dual_coord.rs @@ -17,10 +17,10 @@ use crate::element::{Drawable, PointCollection}; use plotters_backend::{BackendCoord, DrawingBackend}; /// The chart context that has two coordinate system attached. -/// This situation is quite common, for example, we with two different coodinate system. +/// This situation is quite common, for example, we with two different coordinate 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..997f30d0 100644 --- a/plotters/src/chart/series.rs +++ b/plotters/src/chart/series.rs @@ -72,6 +72,7 @@ Useful to specify the position of the series label. See [`ChartContext::configure_series_labels()`] for more information and examples. */ +#[derive(Debug, Clone, PartialEq)] pub enum SeriesLabelPosition { /// Places the series label at the upper left UpperLeft, @@ -101,18 +102,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 +247,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/chart/state.rs b/plotters/src/chart/state.rs index 1ce2f828..55c4056e 100644 --- a/plotters/src/chart/state.rs +++ b/plotters/src/chart/state.rs @@ -50,7 +50,7 @@ impl<'a, DB: DrawingBackend, CT: CoordTranslate> From> impl<'a, DB: DrawingBackend, CT: CoordTranslate> ChartContext<'a, DB, CT> { /// Convert a chart context into a chart state, by doing so, the chart context is consumed and - /// a saved chart state is created for later use. This is typically used in incrmental rendering. See documentation of `ChartState` for more detailed example. + /// a saved chart state is created for later use. This is typically used in incremental rendering. See documentation of `ChartState` for more detailed example. pub fn into_chart_state(self) -> ChartState { self.into() } diff --git a/plotters/src/coord/mod.rs b/plotters/src/coord/mod.rs index 574929d4..b01fc697 100644 --- a/plotters/src/coord/mod.rs +++ b/plotters/src/coord/mod.rs @@ -1,7 +1,7 @@ /*! One of the key features of Plotters is flexible coordinate system abstraction and this module -provides all the abstraction used for the coordinate abstarction of Plotters. +provides all the abstraction used for the coordinate abstraction of Plotters. Generally speaking, the coordinate system in Plotters is responsible for mapping logic data points into pixel based backend coordinate. This task is abstracted by a simple trait called diff --git a/plotters/src/coord/ranged1d/combinators/ckps.rs b/plotters/src/coord/ranged1d/combinators/ckps.rs index 5e1ed72b..cdaaf922 100644 --- a/plotters/src/coord/ranged1d/combinators/ckps.rs +++ b/plotters/src/coord/ranged1d/combinators/ckps.rs @@ -11,8 +11,9 @@ use crate::coord::ranged1d::{AsRangedCoord, DiscreteRanged, KeyPointHint, Ranged /// This decorator allows customized tick mark specifiied by vector. /// See [BindKeyPoints::with_key_points](trait.BindKeyPoints.html#tymethod.with_key_points) /// for details. -/// Note: For any coordinate spec wrapped by this decorator, the maxium number of labels configured by +/// Note: For any coordinate spec wrapped by this decorator, the maximum number of labels configured by /// MeshStyle will be ignored and the key point function will always returns the entire vector +#[derive(Clone)] pub struct WithKeyPoints { inner: Inner, bold_points: Vec, @@ -122,7 +123,7 @@ where impl BindKeyPoints for T {} /// The coordinate decorator that allows customized keypoint algorithms. -/// Normally, all the coordinate spec implements its own key point algorith +/// Normally, all the coordinate spec implements its own key point algorithm /// But this decorator allows you override the pre-defined key point algorithm. /// /// To use this decorator, see [BindKeyPointMethod::with_key_point_func](trait.BindKeyPointMethod.html#tymethod.with_key_point_func) diff --git a/plotters/src/coord/ranged1d/combinators/group_by.rs b/plotters/src/coord/ranged1d/combinators/group_by.rs index 5c0a4e56..28e72ee4 100644 --- a/plotters/src/coord/ranged1d/combinators/group_by.rs +++ b/plotters/src/coord/ranged1d/combinators/group_by.rs @@ -82,16 +82,15 @@ impl Ranged for GroupBy { let idx_iter = (0..hint.bold_points()).map(|x| x * interval); if hint.weight().allow_light_points() && count < hint.bold_points() * 2 { - let outter_ticks = idx_iter; - let outter_tick_size = interval * self.1; - let inner_ticks_per_group = hint.max_num_points() / outter_ticks.len(); - let inner_ticks = - (outter_tick_size + inner_ticks_per_group - 1) / inner_ticks_per_group; - let inner_ticks: Vec<_> = (0..(outter_tick_size / inner_ticks)) + let outer_ticks = idx_iter; + let outer_tick_size = interval * self.1; + let inner_ticks_per_group = hint.max_num_points() / outer_ticks.len(); + let inner_ticks = (outer_tick_size + inner_ticks_per_group - 1) / inner_ticks_per_group; + let inner_ticks: Vec<_> = (0..(outer_tick_size / inner_ticks)) .map(move |x| x * inner_ticks) .collect(); let size = self.0.size(); - return outter_ticks + return outer_ticks .flat_map(|base| inner_ticks.iter().map(move |&ofs| base * self.1 + ofs)) .take_while(|&idx| idx < size) .map(|x| self.0.from_index(x).unwrap()) diff --git a/plotters/src/coord/ranged1d/combinators/linspace.rs b/plotters/src/coord/ranged1d/combinators/linspace.rs index 7f4ac864..14b5ebaa 100644 --- a/plotters/src/coord/ranged1d/combinators/linspace.rs +++ b/plotters/src/coord/ranged1d/combinators/linspace.rs @@ -152,7 +152,7 @@ where } } -/// The coordinate combinator that transform a continous coordinate to a discrete coordinate +/// The coordinate combinator that transform a continuous coordinate to a discrete coordinate /// to a discrete coordinate by a giving step. /// /// For example, range `0f32..100f32` is a continuous coordinate, thus this prevent us having a @@ -315,7 +315,7 @@ where } fn from_index(&self, idx: usize) -> Option { - self.grid_value.get(idx).map(Clone::clone) + self.grid_value.get(idx).cloned() } } diff --git a/plotters/src/coord/ranged1d/combinators/logarithmic.rs b/plotters/src/coord/ranged1d/combinators/logarithmic.rs index fee36f37..af9e1398 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); @@ -75,7 +78,7 @@ impl IntoLogRange for Range { } } -/// The logarithmic coodinate decorator. +/// The logarithmic coordinate decorator. /// This decorator is used to make the axis rendered as logarithmically. #[derive(Clone)] pub struct LogRangeExt { @@ -100,7 +103,7 @@ impl LogRangeExt { self } - /// Set the base multipler + /// Set the base multiplier pub fn base(mut self, base: f64) -> Self { if self.base > 1.0 { self.base = base; @@ -148,6 +151,7 @@ impl AsRangedCoord for LogRangeExt { } /// A log scaled coordinate axis +#[derive(Clone)] pub struct LogCoord { linear: RangedCoordf64, logic: Range, @@ -178,7 +182,7 @@ impl LogCoord { let a = V::from_f64(fv + self.zero_point); let b = V::from_f64(self.zero_point); - (V::as_f64(&a) - V::as_f64(&b)).abs() < std::f64::EPSILON + (V::as_f64(&a) - V::as_f64(&b)).abs() < f64::EPSILON } } @@ -253,7 +257,7 @@ impl Ranged for LogCoord { } } -/// The logarithmic coodinate decorator. +/// The logarithmic coordinate decorator. /// This decorator is used to make the axis rendered as logarithmically. #[deprecated(note = "LogRange is deprecated, use IntoLogRange trait method instead")] #[derive(Clone)] diff --git a/plotters/src/coord/ranged1d/combinators/nested.rs b/plotters/src/coord/ranged1d/combinators/nested.rs index e4a493ec..379f2d4f 100644 --- a/plotters/src/coord/ranged1d/combinators/nested.rs +++ b/plotters/src/coord/ranged1d/combinators/nested.rs @@ -45,6 +45,7 @@ impl From for NestedValue { /// for each value in discrete value, there is a secondary coordinate system. /// And the value is defined as a tuple of primary coordinate value and secondary /// coordinate value +#[derive(Clone)] pub struct NestedRange { primary: Primary, secondary: Vec, diff --git a/plotters/src/coord/ranged1d/discrete.rs b/plotters/src/coord/ranged1d/discrete.rs index 074eece8..8b5da4b6 100644 --- a/plotters/src/coord/ranged1d/discrete.rs +++ b/plotters/src/coord/ranged1d/discrete.rs @@ -20,8 +20,8 @@ where /// Map a value to the index /// - /// Note: This function doesn't guareentee return None when the value is out of range. - /// The only way to confirm the value is in the range is to examing the return value isn't + /// Note: This function doesn't guarantee return None when the value is out of range. + /// The only way to confirm the value is in the range is to examining the return value isn't /// larger than self.size. /// /// - `value`: The value to map @@ -30,11 +30,11 @@ where /// Reverse map the index to the value /// - /// Note: This function doesn't guareentee returning None when the index is out of range. + /// Note: This function doesn't guarantee returning None when the index is out of range. /// /// - `value`: The index to map /// - **returns** The value - // TODO: This doesn't follows rust's naming convention - however, this is a protential breaking + // TODO: This doesn't follows rust's naming convention - however, this is a potential breaking // change, so postpone the fix to the next major release #[allow(clippy::wrong_self_convention)] fn from_index(&self, index: usize) -> Option; @@ -87,13 +87,14 @@ where } /// A `SegmentedCoord` is a decorator on any discrete coordinate specification. -/// This decorator will convert the discrete coordiante in two ways: -/// - Add an extra dummy element after all the values in origianl discrete coordinate -/// - Logically each value `v` from original coordinate system is mapped into an segment `[v, v+1)` where `v+1` denotes the sucessor of the `v` +/// This decorator will convert the discrete coordinate in two ways: +/// - Add an extra dummy element after all the values in original discrete coordinate +/// - Logically each value `v` from original coordinate system is mapped into an segment `[v, v+1)` where `v+1` denotes the successor of the `v` /// - Introduce two types of values `SegmentValue::Exact(value)` which denotes the left end of value's segment and `SegmentValue::CenterOf(value)` which refers the center of the segment. -/// This is used in histogram types, which uses a discrete coordinate as the buckets. The segmented coord always emits `CenterOf(value)` key points, thus it allows all the label and tick marks -/// of the coordinate rendered in the middle of each segment. -/// The coresponding trait [IntoSegmentedCoord](trait.IntoSegmentedCoord.html) is used to apply this decorator to coordinates. +/// This is used in histogram types, which uses a discrete coordinate as the buckets. +/// The segmented coord always emits `CenterOf(value)` key points, thus it allows all the label and tick marks +/// of the coordinate rendered in the middle of each segment. +/// The corresponding trait [IntoSegmentedCoord](trait.IntoSegmentedCoord.html) is used to apply this decorator to coordinates. #[derive(Clone)] pub struct SegmentedCoord(D); diff --git a/plotters/src/coord/ranged1d/mod.rs b/plotters/src/coord/ranged1d/mod.rs index 97664a2f..1b2072c2 100644 --- a/plotters/src/coord/ranged1d/mod.rs +++ b/plotters/src/coord/ranged1d/mod.rs @@ -61,7 +61,7 @@ pub use discrete::{DiscreteRanged, IntoSegmentedCoord, SegmentValue, SegmentedCo /// Since stable Rust doesn't have specialization, it's very hard to make our own trait that /// automatically implemented the value formatter. This trait uses as a marker indicates if we -/// should automatically implement the default value formater based on it's `Debug` trait +/// should automatically implement the default value formatter based on it's `Debug` trait pub trait DefaultValueFormatOption {} /// This makes the ranged coord uses the default `Debug` based formatting @@ -115,7 +115,7 @@ impl KeyPointWeight { /// The trait for a hint provided to the key point algorithm used by the coordinate specs. /// The most important constraint is the `max_num_points` which means the algorithm could emit no more than specific number of key points /// `weight` is used to determine if this is used as a bold grid line or light grid line -/// `bold_points` returns the max number of coresponding bold grid lines +/// `bold_points` returns the max number of corresponding bold grid lines pub trait KeyPointHint { /// Returns the max number of key points fn max_num_points(&self) -> usize; @@ -186,12 +186,12 @@ pub trait Ranged { /// This marker decides if Plotters default [ValueFormatter](trait.ValueFormatter.html) implementation should be used. /// This associated type can be one of the following two types: /// - [DefaultFormatting](struct.DefaultFormatting.html) will allow Plotters to automatically impl - /// the formatter based on `Debug` trait, if `Debug` trait is not impl for the `Self::Value`, - /// [ValueFormatter](trait.ValueFormatter.html) will not impl unless you impl it manually. + /// the formatter based on `Debug` trait, if `Debug` trait is not impl for the `Self::Value`, + /// [ValueFormatter](trait.ValueFormatter.html) will not impl unless you impl it manually. /// /// - [NoDefaultFormatting](struct.NoDefaultFormatting.html) Disable the automatic `Debug` - /// based value formatting. Thus you have to impl the - /// [ValueFormatter](trait.ValueFormatter.html) manually. + /// based value formatting. Thus you have to impl the + /// [ValueFormatter](trait.ValueFormatter.html) manually. /// type FormatOption: DefaultValueFormatOption; diff --git a/plotters/src/coord/ranged1d/types/datetime.rs b/plotters/src/coord/ranged1d/types/datetime.rs index 9b12358c..3ab62d11 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) @@ -127,9 +163,11 @@ impl TimeValue for DateTime { impl TimeValue for NaiveDateTime { type DateType = NaiveDate; + fn date_floor(&self) -> NaiveDate { self.date() } + fn date_ceil(&self) -> NaiveDate { if self.time().num_seconds_from_midnight() > 0 { self.date() + Duration::days(1) @@ -137,6 +175,7 @@ impl TimeValue for NaiveDateTime { self.date() } } + fn earliest_after_date(date: NaiveDate) -> NaiveDateTime { date.and_hms(0, 0, 0) } @@ -144,6 +183,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 +705,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); @@ -727,7 +782,7 @@ impl Ranged for RangedDuration { while current < self.1 { ret.push(current); - current = current + Duration::nanoseconds(period as i64); + current += Duration::nanoseconds(period as i64); } return ret; @@ -766,7 +821,7 @@ impl Ranged for RangedDuration { while current < self.1 { ret.push(current); - current = current + Duration::days(i64::from(days_per_tick)); + current += Duration::days(i64::from(days_per_tick)); } ret @@ -776,7 +831,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 +853,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 +861,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 +869,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 +878,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 +886,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 +1118,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 +1223,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..6a0fd864 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, }; @@ -8,7 +9,7 @@ pub use datetime::{ mod numeric; pub use numeric::{ RangedCoordf32, RangedCoordf64, RangedCoordi128, RangedCoordi32, RangedCoordi64, - RangedCoordu128, RangedCoordu32, RangedCoordu64, RangedCoordusize, + RangedCoordisize, RangedCoordu128, RangedCoordu32, RangedCoordu64, RangedCoordusize, }; mod slice; diff --git a/plotters/src/coord/ranged1d/types/numeric.rs b/plotters/src/coord/ranged1d/types/numeric.rs index a4e7b2b6..8a9ab2d6 100644 --- a/plotters/src/coord/ranged1d/types/numeric.rs +++ b/plotters/src/coord/ranged1d/types/numeric.rs @@ -87,6 +87,14 @@ macro_rules! make_numeric_coord { return limit.1; } + if logic_length.is_infinite() { + if logic_length.is_sign_positive() { + return limit.1; + } else { + return limit.0; + } + } + if actual_length > 0 { return limit.0 + (actual_length as f64 * logic_length + 1e-3).floor() as i32; } else { @@ -117,7 +125,7 @@ macro_rules! gen_key_points_comp { assert!(!(range.0.is_nan() || range.1.is_nan())); - if (range.0 - range.1).abs() < std::f64::EPSILON { + if (range.0 - range.1).abs() < f64::EPSILON { return vec![range.0 as $type]; } @@ -133,7 +141,7 @@ macro_rules! gen_key_points_comp { } else { a - (a / b).ceil() * b }; - if (ret - b).abs() < std::f64::EPSILON { + if (ret - b).abs() < f64::EPSILON { 0.0 } else { ret @@ -183,7 +191,7 @@ macro_rules! gen_key_points_comp { let left_base = (left / value_granularity).floor() * value_granularity; let mut left_relative = left - left_base; let right = range.1 - rem_euclid(range.1, scale); - while (right - left_relative - left_base) >= -std::f64::EPSILON { + while (right - left_relative - left_base) >= -f64::EPSILON { let new_left_relative = (left_relative / value_granularity).round() * value_granularity; if new_left_relative < 0.0 { @@ -354,14 +362,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 +412,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] @@ -414,7 +422,7 @@ mod test { } #[test] - fn regession_test_issue_358_key_points_no_hang() { + fn regression_test_issue_358_key_points_no_hang() { let coord: RangedCoordf64 = (-200.0..801.0).into(); let points = coord.key_points(500); assert!(points.len() <= 500); @@ -448,6 +456,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/coord/ranged2d/cartesian.rs b/plotters/src/coord/ranged2d/cartesian.rs index 5052a62f..57d2240f 100644 --- a/plotters/src/coord/ranged2d/cartesian.rs +++ b/plotters/src/coord/ranged2d/cartesian.rs @@ -2,9 +2,9 @@ The 2-dimensional cartesian coordinate system. This module provides the 2D cartesian coordinate system, which is composed by two independent - ranged 1D coordinate sepcification. + ranged 1D coordinate specification. - This types of coordinate system is used by the chart constructed with [ChartBuilder::build_cartesian_2d](../../chart/ChartBuilder.html#method.build_cartesian_2d). + This type of coordinate system is used by the chart constructed with [ChartBuilder::build_cartesian_2d](../../chart/ChartBuilder.html#method.build_cartesian_2d). */ use crate::coord::ranged1d::{KeyPointHint, Ranged, ReversibleRanged}; diff --git a/plotters/src/data/data_range.rs b/plotters/src/data/data_range.rs index 445260b9..3d42eec4 100644 --- a/plotters/src/data/data_range.rs +++ b/plotters/src/data/data_range.rs @@ -16,9 +16,9 @@ use num_traits::{One, Zero}; /// let range = fitting_range(&data); /// assert_eq!(range, std::ops::Range { start: -2, end: 14 }); /// ``` -pub fn fitting_range<'a, T: 'a, I: IntoIterator>(iter: I) -> Range +pub fn fitting_range<'a, T, I: IntoIterator>(iter: I) -> Range where - T: Zero + One + PartialOrd + Clone, + T: 'a + Zero + One + PartialOrd + Clone, { let (mut lb, mut ub) = (None, None); diff --git a/plotters/src/data/quartiles.rs b/plotters/src/data/quartiles.rs index 054f51d1..78613dad 100644 --- a/plotters/src/data/quartiles.rs +++ b/plotters/src/data/quartiles.rs @@ -19,7 +19,7 @@ impl Quartiles { assert!(0_f64 <= pct); let hundred = 100_f64; assert!(pct <= hundred); - if (pct - hundred).abs() < std::f64::EPSILON { + if (pct - hundred).abs() < f64::EPSILON { return s[s.len() - 1].into(); } let length = (s.len() - 1) as f64; diff --git a/plotters/src/drawing/area.rs b/plotters/src/drawing/area.rs index 2e5c3fe3..e8981fea 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, @@ -260,12 +258,12 @@ impl DrawingArea { /// Compute the relative size based on the drawing area's height pub fn relative_to_height(&self, p: f64) -> f64 { - f64::from((self.rect.y1 - self.rect.y0).max(0)) * (p.min(1.0).max(0.0)) + f64::from((self.rect.y1 - self.rect.y0).max(0)) * (p.clamp(0.0, 1.0)) } /// Compute the relative size based on the drawing area's width pub fn relative_to_width(&self, p: f64) -> f64 { - f64::from((self.rect.x1 - self.rect.x0).max(0)) * (p.min(1.0).max(0.0)) + f64::from((self.rect.x1 - self.rect.x0).max(0)) * (p.clamp(0.0, 1.0)) } /// Get the pixel range of this area @@ -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]; @@ -671,13 +669,13 @@ mod drawing_area_tests { for row in 0..=nyb { for col in 0..=nxb { let get_bp = |full, limit, id| { - (if id == 0 { + if id == 0 { 0 } else if id > limit { 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/drawing/mod.rs b/plotters/src/drawing/mod.rs index 9e32d913..5c055fb8 100644 --- a/plotters/src/drawing/mod.rs +++ b/plotters/src/drawing/mod.rs @@ -6,7 +6,7 @@ The low-level drawing abstraction, the module defines the `DrawingBackend` trait It exposes a set of functions which allows basic shape, such as pixels, lines, rectangles, circles, to be drawn on the screen. The low-level API uses the pixel based coordinate. -The high-level API is built on the top of high-level API. The `DrawingArea` type exposes the high-level drawing API to the remianing part +The high-level API is built on the top of high-level API. The `DrawingArea` type exposes the high-level drawing API to the remaining part of Plotters. The basic drawing blocks are composable elements, which can be defined in logic coordinate. To learn more details about the [coordinate abstraction](../coord/index.html) and [element system](../element/index.html). */ diff --git a/plotters/src/element/basic_shapes.rs b/plotters/src/element/basic_shapes.rs index 7c0b9d4f..c43af473 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"); } @@ -160,6 +418,20 @@ impl Rectangle { self.margin = (t, b, l, r); self } + + /// Get the points of the rectangle + /// - returns the element points + pub fn get_points(&self) -> (&Coord, &Coord) { + (&self.points[0], &self.points[1]) + } + + /// Set the style of the rectangle + /// - `style`: The shape style + /// - returns a mut reference to the rectangle + pub fn set_style>(&mut self, style: S) -> &mut Self { + self.style = style.into(); + self + } } impl<'a, Coord> PointCollection<'a, Coord> for &'a Rectangle { @@ -199,7 +471,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 +491,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 +556,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 +565,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 +625,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/image.rs b/plotters/src/element/image.rs index f50ce77b..6c31c2d8 100644 --- a/plotters/src/element/image.rs +++ b/plotters/src/element/image.rs @@ -89,7 +89,7 @@ impl<'a, Coord, P: PixelFormat> BitMapElement<'a, Coord, P> { /// - `size`: The size of the bitmap /// - `buf`: The buffer to use /// - **returns**: The newly created image element, if the buffer isn't fit the image - /// dimension, this will returns an `None`. + /// dimension, this will returns an `None`. pub fn with_owned_buffer(pos: Coord, size: (u32, u32), buf: Vec) -> Option { if buf.len() < (size.0 * size.1) as usize * P::PIXEL_SIZE { return None; @@ -109,7 +109,7 @@ impl<'a, Coord, P: PixelFormat> BitMapElement<'a, Coord, P> { /// - `size`: The size of the bitmap /// - `buf`: The buffer to use /// - **returns**: The newly created image element, if the buffer isn't fit the image - /// dimension, this will returns an `None`. + /// dimension, this will returns an `None`. pub fn with_mut(pos: Coord, size: (u32, u32), buf: &'a mut [u8]) -> Option { if buf.len() < (size.0 * size.1) as usize * P::PIXEL_SIZE { return None; @@ -123,14 +123,14 @@ impl<'a, Coord, P: PixelFormat> BitMapElement<'a, Coord, P> { }) } - /// Create a new bitmap element with a shared borrowed buffer. This means if we want to modifiy + /// Create a new bitmap element with a shared borrowed buffer. This means if we want to modify /// the content of the image, the buffer is automatically copied /// /// - `pos`: The left upper coordinate of the elelent /// - `size`: The size of the bitmap /// - `buf`: The buffer to use /// - **returns**: The newly created image element, if the buffer isn't fit the image - /// dimension, this will returns an `None`. + /// dimension, this will returns an `None`. pub fn with_ref(pos: Coord, size: (u32, u32), buf: &'a [u8]) -> Option { if buf.len() < (size.0 * size.1) as usize * P::PIXEL_SIZE { return None; diff --git a/plotters/src/element/mod.rs b/plotters/src/element/mod.rs index e2790051..921b2c0f 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; @@ -214,7 +218,7 @@ use crate::drawing::Rect; /// /// However, /// [Generic Associated Types](https://github.com/rust-lang/rfcs/blob/master/text/1598-generic_associated_types.md) -/// is far away from stablize. +/// is far away from stabilize. /// So currently we have the following workaround: /// /// Instead of implement the PointCollection trait on the element type itself, it implements on the diff --git a/plotters/src/element/pie.rs b/plotters/src/element/pie.rs index 95298345..964fe959 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, } } @@ -77,7 +79,7 @@ impl<'a, Label: Display> Pie<'a, (i32, i32), Label> { self.start_radian = start_angle.to_radians(); } - /// + /// Set the label style. pub fn label_style>>(&mut self, label_style: T) { self.label_style = label_style.into(); } @@ -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/element/text.rs b/plotters/src/element/text.rs index ca813c7c..9baa2016 100644 --- a/plotters/src/element/text.rs +++ b/plotters/src/element/text.rs @@ -1,5 +1,4 @@ use std::borrow::Borrow; -use std::i32; use super::{Drawable, PointCollection}; use crate::style::{FontDesc, FontResult, LayoutBox, TextStyle}; @@ -116,6 +115,10 @@ impl<'a, Coord, T: Borrow> MultiLineText<'a, Coord, T> { } } +// Rewrite of the layout function for multiline-text. It crashes when UTF-8 is used +// instead of ASCII. Solution taken from: +// https://stackoverflow.com/questions/68122526/splitting-a-utf-8-string-into-chunks +// and modified for our purposes. fn layout_multiline_text<'a, F: FnMut(&'a str)>( text: &'a str, max_width: u32, @@ -126,32 +129,61 @@ fn layout_multiline_text<'a, F: FnMut(&'a str)>( if max_width == 0 || line.is_empty() { func(line); } else { - let mut remaining = &line[0..]; + let mut indices = line.char_indices().map(|(idx, _)| idx).peekable(); - while !remaining.is_empty() { - let mut left = 0; - while left < remaining.len() { - let width = font.box_size(&remaining[0..=left]).unwrap_or((0, 0)).0 as i32; + let it = std::iter::from_fn(|| { + let start_idx = match indices.next() { + Some(idx) => idx, + None => return None, + }; + // iterate over indices + for idx in indices.by_ref() { + let substring = &line[start_idx..idx]; + let width = font.box_size(substring).unwrap_or((0, 0)).0 as i32; if width > max_width as i32 { break; } - left += 1; } - if left == 0 { - left += 1; - } + let end_idx = match indices.peek() { + Some(idx) => *idx, + None => line.bytes().len(), + }; - let cur_line = &remaining[..left]; - remaining = &remaining[left..]; + Some(&line[start_idx..end_idx]) + }); - func(cur_line); + for chunk in it { + func(chunk); } } } } +// Only run the test on Linux because the default font is different +// on other platforms, causing different multiline splits. +#[cfg(all(feature = "ttf", target_os = "linux"))] +#[test] +fn test_multi_layout() { + use plotters_backend::{FontFamily, FontStyle}; + + let font = FontDesc::new(FontFamily::SansSerif, 20 as f64, FontStyle::Bold); + + layout_multiline_text("öäabcde", 40, font, |txt| { + println!("Got: {}", txt); + assert!(txt == "öäabc" || txt == "de"); + }); + + let font = FontDesc::new(FontFamily::SansSerif, 20 as f64, FontStyle::Bold); + layout_multiline_text("öä", 100, font, |txt| { + // This does not divide the line, but still crashed in the previous implementation + // of layout_multiline_text. So this test should be reliable + println!("Got: {}", txt); + assert_eq!(txt, "öä") + }); +} + impl<'a, T: Borrow> MultiLineText<'a, BackendCoord, T> { /// Compute the line layout pub fn compute_line_layout(&self) -> FontResult> { diff --git a/plotters/src/evcxr.rs b/plotters/src/evcxr.rs index 8117d35f..9d7b9666 100644 --- a/plotters/src/evcxr.rs +++ b/plotters/src/evcxr.rs @@ -2,8 +2,11 @@ use crate::coord::Shift; use crate::drawing::{DrawingArea, IntoDrawingArea}; use plotters_backend::DrawingBackend; use plotters_svg::SVGBackend; +use std::fs::File; +use std::io::Write; #[cfg(feature = "evcxr_bitmap")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "evcxr_bitmap")))] use plotters_bitmap::BitMapBackend; /// The wrapper for the generated SVG @@ -45,17 +48,37 @@ pub fn evcxr_figure< SVGWrapper(buffer, "".to_string()) } +/// An evcxr figure that can save to the local file system and render in a notebook. +pub fn evcxr_figure_with_saving< + Draw: FnOnce(DrawingArea) -> Result<(), Box>, +>( + filename: &str, + size: (u32, u32), + draw: Draw, +) -> SVGWrapper { + let mut buffer = "".to_string(); + let root = SVGBackend::with_string(&mut buffer, size).into_drawing_area(); + draw(root).expect("Drawing failure"); + + let mut file = File::create(filename).expect("Unable to create file"); + file.write_all(buffer.as_bytes()) + .expect("Unable to write data"); + + SVGWrapper(buffer, "".to_string()) +} /// 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; - let mut buf = Vec::new(); - buf.resize((size.0 as usize) * (size.1 as usize) * PIXEL_SIZE, 0); + const PIXEL_SIZE: usize = 3; + + let mut buf = vec![0; (size.0 as usize) * (size.1 as usize) * PIXEL_SIZE]; + let root = BitMapBackend::with_buffer(&mut buf, size).into_drawing_area(); draw(root).expect("Drawing failure"); let mut buffer = "".to_string(); diff --git a/plotters/src/lib.rs b/plotters/src/lib.rs index 873288b2..230c679f 100644 --- a/plotters/src/lib.rs +++ b/plotters/src/lib.rs @@ -1,7 +1,9 @@ #![warn(missing_docs)] +#![allow(clippy::type_complexity)] +#![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 +18,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 +36,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Multiple Plot - [code] + [code]
@@ -44,7 +46,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Candlestick Plot - [code] + [code]
@@ -54,7 +56,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Histogram - [code] + [code]
@@ -82,7 +84,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Mandelbrot set - [code] + [code]
@@ -112,7 +114,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Histogram with Scatter - [code] + [code]
@@ -122,7 +124,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Dual Y-Axis Example - [code] + [code]
@@ -132,7 +134,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
The Matplotlib Matshow Example - [code] + [code]
@@ -142,7 +144,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
The Sierpinski Carpet - [code] + [code]
@@ -152,7 +154,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
The 1D Gaussian Distribution - [code] + [code]
@@ -162,7 +164,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
The 1D Gaussian Distribution - [code] + [code]
@@ -172,7 +174,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Monthly Time Coordinate - [code] + [code]
@@ -182,7 +184,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Monthly Time Coordinate - [code] + [code]
@@ -192,7 +194,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Koch Snowflake - [code] + [code]
@@ -203,7 +205,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Koch Snowflake Animation - [code] + [code]
@@ -214,7 +216,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Drawing on a Console - [code] + [code]
@@ -224,7 +226,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
Drawing bitmap on chart - [code] + [code]
@@ -234,7 +236,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
The boxplot demo - [code] + [code]
@@ -244,7 +246,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
3D plot rendering - [code] + [code]
@@ -254,7 +256,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
2-Var Gussian Distribution PDF - [code] + [code]
@@ -264,7 +266,7 @@ including bitmap, vector graph, piston window, GTK/Cairo and WebAssembly.
COVID-19 Visualization - [code] + [code]
@@ -280,8 +282,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 +305,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 +348,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.6", 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 +398,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 +408,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 -can be very easy to use. + 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 -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. +* **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 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 -very useful for visualization on a web page and would have a huge performance improvement comparing to Javascript. +* **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 +475,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 +500,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 +528,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 +571,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 +582,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,19 +629,19 @@ 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 Plotters now supports use features to control the backend dependencies. By default, `BitMapBackend` and `SVGBackend` are supported, -use `default_features = false` in the dependency description in `Cargo.toml` and you can cherry-pick the backend implementations. +use `default-features = false` in the dependency description in `Cargo.toml` and you can cherry-pick the backend implementations. - `svg` Enable the `SVGBackend` - `bitmap` Enable the `BitMapBackend` @@ -650,34 +650,63 @@ 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. -This behavior can also be turned off by setting `default_features = false`. +This behavior can also be turned off by setting `default-features = false`. ### List of Features This is the full list of features that is defined by `Plotters` crate. -Use `default_features = false` to disable those default enabled features, +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 +744,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 +758,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,14 +798,12 @@ 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")] -pub use palette; - /// The module imports the most commonly used types and modules in Plotters pub mod prelude { // Chart related types @@ -798,6 +825,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 +837,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 +876,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 +894,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 +906,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 +923,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..913366a7 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. Can be used to draw simple dashed and dotted lines. +/// +/// If you want to use more complex shapes as points in the line, you can use `plotters::series::line_series::DottedLineSeries`. +/// +/// # Examples +/// +/// Dashed line: +/// ```Rust +/// chart_context +/// .draw_series(DashedLineSeries::new( +/// data_series, +/// 5, /* size = length of dash */ +/// 10, /* spacing */ +/// ShapeStyle { +/// color: BLACK.mix(1.0), +/// filled: false, +/// stroke_width: 1, +/// }, +/// )) +/// .unwrap(); +/// ``` +/// +/// Dotted line: (keep `size` and `stroke_width` the same to achieve dots) +/// ```Rust +/// chart_context +/// .draw_series(DashedLineSeries::new( +/// data_series, +/// 1, /* size = length of dash */ +/// 4, /* spacing, best to keep this at least 1 larger than size */ +/// ShapeStyle { +/// color: BLACK.mix(1.0), +/// filled: false, +/// stroke_width: 1, +/// }, +/// )) +/// .unwrap(); +/// ``` +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::*; @@ -95,7 +219,7 @@ mod test { m.check_draw_path(|c, s, _path| { assert_eq!(c, RED.to_rgba()); assert_eq!(s, 3); - // TODO when cleanup the backend coordinate defination, then we uncomment the + // TODO when cleanup the backend coordinate definition, then we uncomment the // following check //for i in 0..100 { // assert_eq!(path[i], (i as i32 * 2, 199 - i as i32 * 2)); @@ -103,8 +227,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 +239,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/series/surface.rs b/plotters/src/series/surface.rs index 2307e32f..2621f4f1 100644 --- a/plotters/src/series/surface.rs +++ b/plotters/src/series/surface.rs @@ -213,7 +213,7 @@ where } else { self.vidx_1 += 1; self.vidx_2 = 1; - if let (Some(b0), Some(b1)) = (self.free_var_2.get(0), self.free_var_2.get(1)) { + if let (Some(b0), Some(b1)) = (self.free_var_2.first(), self.free_var_2.get(1)) { (b0, b1) } else { return None; diff --git a/plotters/src/style/color.rs b/plotters/src/style/color.rs index 7e372cd1..2a5fbf02 100644 --- a/plotters/src/style/color.rs +++ b/plotters/src/style/color.rs @@ -137,9 +137,9 @@ impl Color for HSLColor { #[allow(clippy::many_single_char_names)] fn to_backend_color(&self) -> BackendColor { let (h, s, l) = ( - self.0.min(1.0).max(0.0), - self.1.min(1.0).max(0.0), - self.2.min(1.0).max(0.0), + self.0.clamp(0.0, 1.0), + self.1.clamp(0.0, 1.0), + self.2.clamp(0.0, 1.0), ); if s == 0.0 { diff --git a/plotters/src/style/colors/colormaps.rs b/plotters/src/style/colors/colormaps.rs new file mode 100644 index 00000000..35ebddbf --- /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 this 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/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..5d5a7209 100644 --- a/plotters/src/style/font/ttf.rs +++ b/plotters/src/style/font/ttf.rs @@ -1,7 +1,6 @@ use std::borrow::{Borrow, Cow}; use std::cell::RefCell; use std::collections::HashMap; -use std::i32; use std::sync::{Arc, RwLock}; use lazy_static::lazy_static; @@ -82,8 +81,8 @@ 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 } @@ -126,7 +125,7 @@ fn load_font_data(face: FontFamily, style: FontStyle) -> FontResult { font_object_cache .borrow() .get(Borrow::::borrow(&key)) - .map(Clone::clone) + .cloned() }) { return Ok(font_object); } @@ -134,12 +133,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 +267,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 +315,6 @@ mod test { // TODO: Check they are the same - return Ok(()); + Ok(()) } } diff --git a/plotters/src/style/font/web.rs b/plotters/src/style/font/web.rs index e70e7b1a..7af99965 100644 --- a/plotters/src/style/font/web.rs +++ b/plotters/src/style/font/web.rs @@ -34,7 +34,7 @@ impl FontData for FontDataInternal { let body = document.body().unwrap(); let span = document.create_element("span").unwrap(); span.set_text_content(Some(text)); - span.set_attribute("style", &format!("display: inline-block; font-family:{}; font-size: {}px; position: fixed; top: 100%", self.0, size)).unwrap(); + span.set_attribute("style", &format!("display: inline-block; font-family:{}; font-style:{}; font-size: {}px; position: fixed; top: 100%", self.0, self.1, size)).unwrap(); let span = span.into(); body.append_with_node_1(&span).unwrap(); let elem = JsCast::dyn_into::(span).unwrap(); 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/shape.rs b/plotters/src/style/shape.rs index 389cc75c..97ac6b6e 100644 --- a/plotters/src/style/shape.rs +++ b/plotters/src/style/shape.rs @@ -2,7 +2,7 @@ use super::color::{Color, RGBAColor}; use plotters_backend::{BackendColor, BackendStyle}; /// Style for any shape -#[derive(Copy, Clone)] +#[derive(Copy, Clone, Debug, PartialEq)] pub struct ShapeStyle { /// Specification of the color. pub color: RGBAColor,