GithubHelp home page GithubHelp logo

igiagkiozis / plotly Goto Github PK

View Code? Open in Web Editor NEW
947.0 16.0 90.0 42.18 MB

Plotly for Rust

Home Page: https://docs.rs/plotly

License: Other

Rust 99.31% HTML 0.69%
plot rust chart financial financial-analysis data-visualization data-vizualisation plotly plotlyjs scatter

plotly's Introduction

Plotly.rs

Plotly for Rust

Build status Crates.io Downloads Documentation Code coverage

Table of Contents

Introduction

A plotting library for Rust powered by Plotly.js.

Documentation and numerous interactive examples are available in the Plotly.rs Book, the examples/ directory and docs.rs.

For changes since the last version, please consult the changelog.

Basic Usage

Add this to your Cargo.toml:

[dependencies]
plotly = "0.8.4"

Exporting an Interactive Plot

Any figure can be saved as an HTML file using the Plot.write_html() method. These HTML files can be opened in any web browser to access the fully interactive figure.

use plotly::{Plot, Scatter};

let mut plot = Plot::new();
let trace = Scatter::new(vec![0, 1, 2], vec![2, 1, 0]);
plot.add_trace(trace);

plot.write_html("out.html");

By default, the Plotly JavaScript library will be included via CDN, which results in a smaller filesize, but slightly slower first load as the JavaScript library has to be downloaded first. To instead embed the JavaScript library (several megabytes in size) directly into the HTML file, the following can be done:

// <-- Create a `Plot` -->

plot.use_local_plotly();
plot.write_html("out.html");

If you only want to view the plot in the browser quickly, use the Plot.show() method.

// <-- Create a `Plot` -->

plot.show(); // The default web browser will open, displaying an interactive plot

Exporting a Static Image

To save a plot as a static image, the kaleido feature is required:

# Cargo.toml

[dependencies]
plotly = { version = "0.8.4", features = ["kaleido"] }

With this feature enabled, plots can be saved as any of png, jpeg, webp, svg, pdf and eps. Note that the plot will be a static image, i.e. they will be non-interactive.

The Kaleido binary is downloaded for your system's architecture at compile time from the official Kaleido release page. This library currently supports x86_64 on Linux and Windows, and both x86_64 and aarch64 on macOS.

Exporting a simple plot looks like this:

use plotly::{ImageFormat, Plot};

let mut plot = Plot::new();
let trace = Scatter::new(vec![0, 1, 2], vec![2, 1, 0]);
plot.add_trace(trace);

plot.write_image("out.png", ImageFormat::PNG, 800, 600, 1.0);

Usage Within a Wasm Environment

Using Plotly.rs in a Wasm-based frontend framework is possible by enabling the wasm feature:

# Cargo.toml

[dependencies]
plotly = { version = "0.8.4", features = ["wasm"] }

First, make sure that you have the Plotly JavaScript library in your base HTML template:

 <!-- index.html -->

<!doctype html>
<html lang="en">
    <head>
        <!-- snip -->
        <script src="https://cdn.plot.ly/plotly-2.14.0.min.js"></script>
    </head>
    <!-- snip -->
</html>

A simple Plot component would look as follows, using Yew as an example frontend framework:

use plotly::{Plot, Scatter};
use yew::prelude::*;


#[function_component(PlotComponent)]
pub fn plot_component() -> Html {
    let p = yew_hooks::use_async::<_, _, ()>({
        let id = "plot-div";
        let mut plot = Plot::new();
        let trace = Scatter::new(vec![0, 1, 2], vec![2, 1, 0]);
        plot.add_trace(trace);

        async move {
            plotly::bindings::new_plot(id, &plot).await;
            Ok(())
        }
    });

    
        use_effect_with_deps(move |_| {
            p.run();
            || ()
        }, (),
    );
    

    html! {
        <div id="plot-div"></div>
    }
}

More detailed standalone examples can be found in the examples/ directory.

Crate Feature Flags

The following feature flags are available:

kaleido

Adds plot save functionality to the following formats: png, jpeg, webp, svg, pdf and eps.

plotly_image

Adds trait implementations so that image::RgbImage and image::RgbaImage can be used more directly with the plotly::Image trace.

plotly_ndarray

Adds support for creating plots directly using ndarray types.

wasm

Enables compilation for the wasm32-unknown-unknown target and provides access to a bindings module containing wrappers around functions exported by the plotly.js library.

Contributing

  • If you've spotted a bug or would like to see a new feature, please submit an issue on the issue tracker.

  • Pull requests are welcome, see the contributing guide for more information.

License

Plotly.rs is distributed under the terms of the MIT license.

See LICENSE-MIT, and COPYRIGHT for details.

plotly's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

plotly's Issues

Plot 3D scatter and line plots

The zoomable 3D view with the hover info has been of great value to me in my past when working with python.
I went ahead and enabled these features and examples in my fork.
Additionally I added an example for the surface plot, that is already supported, but not advertised.
Is a pull-request welcome for this?
Greetings!

plotly_kaleido build.rs script breaks due to ruget compilation failure

I raised an issue with ruget (ksk001100/ruget#6). I'm raising an issue here too in case this doesn't get fixed.

Compilation of ruget is currently failing due to a breaking change with a dependency:

error[E0599]: no method named `usage` found for struct `Flag` in the current scope
  --> /home/scipi/.cargo/registry/src/github.com-1ecc6299db9ec823/ruget-0.4.2/src/main.rs:56:14
   |
56 |             .usage("--output, -o: ruget [url] --output [file name]")
   |              ^^^^^ method not found in `Flag`

Subsequently, this breaks building plotly_kaleido from scratch.

Remove uneeded dependencies

version:0.5.0
(I know am early sorry)
Dependencies like csv and itertools are only needed for examples and hence not needed for functioning of the crate
This could reduce the overall size footprint of the crate since its calling dependencies not needed

Display hundereds of plots

Yesterday I tried to write around 700 plots to an HTML file via calling to_inline_html() this many times into a vector of strings and then writing them all to an HTML template that only includes plotly.js once. My browser couldn't handle the resulting file very well. It is very slow. Are there any known tricks to make plotly behave more snappy in such situations? Or is this a complete misuse of the library on my part?

Margin right

pub struct Margin {

With the above we are able to adjust the left, top, and bottom largins. Can we add the right margin too? If you're happy to accept pull requests, I could take a look in future

Stack overflows when adding colorbar to plot

Hi, it's enjoyable to use this crate in plotting some scientific figures, and the experience was pleasant.

Just now, I found it crashed when adding color bar to the plot and I'm not sure if this was a matter of my code. Would it be possible to bother you have a look at it?

Here is the MWE:

use plotly;

fn main() {
    let x = (0 .. 100).collect::<Vec<_>>();
    let y = x.iter().map(|v| v * v).collect::<Vec<_>>();
    let c = x.iter().map(|v| (*v as f64).sqrt()).collect::<Vec<_>>();

    let tr = plotly::Scatter::new(x, y)
        .mode(plotly::common::Mode::Markers)
        .marker(plotly::common::Marker::new()
                .color_bar(plotly::common::ColorBar::new())
                .color_scale(plotly::common::ColorScale::Palette(plotly::common::ColorScalePalette::Jet))
                .color_array(c));

    let mut plot = plotly::Plot::new();
    plot.add_trace(tr);
    plot.use_local_plotly();

    plot.show();
}

And it crashed:

thread 'main' has overflowed its stack
fatal runtime error: stack overflow
[1]    39611 abort      cargo run --release

Here is my environment:

  • macOS 10.15.7
  • rustc 1.59 stable
  • plotly 0.7

Real time plotting

Thanks for the great library! Is there a good way to rapidly update plots for displaying realtime data? Looks like I can call plot.show() repeatedly, but that seems pretty sub-optimal.

Add code coverage for tests

It would be really good to boost test coverage throughout the library, and one way to monitor that would be to use something like cargo-llvm-cov and codecov.io.

I've put together a small PR which adds the necessary steps to the two current workflow .yml files.

It would be necessary for this repo to add a 3rd party integration to codecov.io.

Attempting to save in PNG format causes panic

Hi,

I have this in Cargo.toml:

plotly = { version = "0.6", features = ["kaleido"] }

And, following the instructions, this in my code: plot.save(filename, ImageFormat::PNG, 1024, 768, 1.0);

The program crashes with this:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 2, kind: NotFound, message: "No such file or directory" }', /home/jgoerzen/.cargo/registry/src/github.com-1ecc6299db9ec823/plotly_kaleido-0.2.0/src/lib.rs:97:13

That backtrace wasn't much help, but strace was:

21466 lstat("/home", {st_mode=S_IFDIR|0755, st_size=10, ...}) = 0
21466 lstat("/home/jgoerzen", {st_mode=S_IFDIR|0755, st_size=722, ...}) = 0
21466 lstat("/home/jgoerzen/tree", {st_mode=S_IFDIR|0755, st_size=248, ...}) = 0
21466 lstat("/home/jgoerzen/tree/plotly_kaleido", 0x7ffd64e387b0) = -1 ENOENT (No such file or directory)

The current working directory was a different one under /home/jgoerzen/tree.

Why it expects ../plotly_kaleido to exist, I don't know. What's supposed to be there, I also don't know. The plotly documentation said there was some additional configuration necessary for plotly_kaleido but the plotly_kaleido documentation doesn't say what it is. I couldn't find any documentation for how to set up plotly_kaleido or why it would be looking for something in ...

Thanks for your work on this!

offline mode

There doesn't seem to be an offline mode for plotly.rs. While having a silly large html file that includes plotlyjs is not great for most use-cases, being able to look at plots when without web access can be great.
Is this a feature that would welcome?

Expose inline html as a String

Exposing the html/javascript generated could help build dashboards with some rust web stack

let trace1 = Scatter::new(vec![1, 2, 3, 4], vec![10, 15, 13, 17])
       .name("trace1")
       .mode(Mode::Markers);
let mut plot = Plot::new();
plot.add_trace(trace1);
println!("{}", plot.to_inline_html());

Could have a result like

<div id="SomePlotlyID" />
<script>
//Javascript generated
</script>

NumOrString trait not implemented for f32

NumOfString trait implementation is missing for f32 type, preventing from using it in defining axis ranges:

let (xmin:f32, xmax:f32) = some_func();
...
let layout = plotly::Layout::new()
 .x_axis(Axis::new().range(vec![xmin, xmax]).auto_range(false))

results in compilation error:

the trait `ptly::plotly::private::NumOrString` is not implemented for `f32`

requiring manually casting f32 to f64:

...
.x_axis(Axis::new().range(vec![xmin as f64, xmax as f64]).auto_range(false))
...

that looks less ergonomic.

Animation support like for python

This is a feature request for supporting a animated plot like seen in this python example.
I would expect it to work by giving for x and y a slice of slices or a slice of Vecs instead of a single slice.
Given this python example:

import plotly.express as px
df = px.data.gapminder()
px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country",
           size="pop", color="continent", hover_name="country",
           log_x=True, size_max=55, range_x=[100,100000], range_y=[25,90])

A usage example could look like the following code:

use plotly::{common::Mode,Plot,Scatter};
fn main() -> Result<(),BoxErr> {
    // Four different time points
    let time = vec![1.0,2.0,3.0,4.0]; 
    // For each timepoint generate data. This could be a position for example.
    let mut x = Vec::with_capacity(time.len());
    for i in 0..time.len() {
        x.push((0..1_000).map(|x|x as f64*0.1).collect::<Vec<f64>>());
    }
    // For each timepoint evaluate some function at each position
    let mut y = Vec::with_capacity(time.len());
    for (i,xi) in x.iter().enumerate() {
        y.push(
            xi.iter().map(|xk| xk*xk + time[i]).collect::<Vec<f64>>()
        );
    }
    // Generate traces from the data
    let traces = x.into_iter().zip(y).map(|(x,y)| Scatter::new(x,y).mode(Mode::Lines)).collect::<Vec<_>>();
    // Plot the data and animate the plot with respect to time
    let mut plot = Plot::new();
    plot.add_traces(traces).animate_by(time);
    plot.show();
    Ok(())
}

Update Readme

It would be good to include a quick "getting started" section and a couple of example output images, to complement that which is in the Book/API docs already.

Request feature: Scatter3D

I've noticed that the code has already been implemented and merged to dev branch #66. But in version 0.7.0, there is still no Scatter3D available. Please merge dev to master, thanks!

Add pie and horizontal bar charts

I saw a similar issue to this opened before, so I thought it would be OK to add it here. Do you have plans on adding the pie and horizontal bar chart options from plotly in the near future? I could not find any examples anywhere for these two types, so I had to presuppose they were not implemented yet. Thanks.

ColorNamed should be Copy/Clone

It's currently not possible to share the ColorNamed across multiple places consistently because the trait impls are missing. I think it should just be the case of adding the derive.

Documentation

This is a great addition to the broader scientific computing ecosystem for Rust.
I've not used plotly.js extensively, and I suspect a bunch of folks would want to try to use this crate without browsing the plotly-documentation.

So I thought I'd attempt to explore this repo and make some documentation here and there. This issue is to gather ideas, strategy, or whatever needs to be taken into account in order to improve the documentation of this crate.

For instance: Is there a dataset prelude that can be used to make examples with?

Separate pure and system-specific (image file export, etc) code to enable the import into wasm-bindgen projects)

System dependencies hinder using this crate in wasm-bindgen projects. What would be the optimal way to separate all the system-related code (templating and exporting image files) from the core "pure" code?
I tried a quick fix by introducing the "system" flag (should probably be named "export"...) and moving Trace trait and adding a smaller PlotData struct identical to Plot but keeping only to_json serialization method, to the new pure module (here Plot is a superset/overlaps with PlotData but can be trivially refactored by e.g. making PlotData a member of the Plot struct: master...antislava:antislava-pure).
The export features are included under the "system" flag (that should probably be enabled by default).

This fix seems to work fine for me now but not sure if this is the best approach here (I'am new to Rust)

License text isn't clear

Plotly for Rust is distributed under the terms of both the MIT license.

MIT and Apache-2.0, or something else?

Plotly.js 2.0 compatibility

Hi there,

I lead the graphing libraries team at Plotly where we're busy working on version 2.0 of Plotly.js. I'm reaching out to folks who we know are "downstream" of Plotly.js to give you a heads-up about the changes so you can let me know if/how disruptive they're likely to be for you :)

Our approach here is not to make gratuitous breaking changes, but mostly to drop support for un/under-used functionality that slows down development for frequently-used functionality. We expect that the vast majority of users of Plotly.js and downstream systems like Plotly.py, Plotly.R, PlotlyJS.jl, Plotly.NET etc will be unaffected by these changes. The tracking issue we've got going is here plotly/plotly.js#5395

The major changes include, at the Javascript layer:

  • dropping IE 9/10 support due to a switch in the Promise polyfill we're using, for security reasons
  • dropping exports of old versions of d3 modules under Plotly.d3 (so we can upgrade them internally)
  • dropping some exports of deprecated methods like Plotly.plot in favour of Plotly.newPlot and Plotly.react

The major changes at the schema layer:

  • dropping support for pointcloud, area and contourgl traces, as well as the legacy polar attributes from scatter like scatter.r and layout.angularaxis
  • dropping the role key from the schema altogether

I'm happy to answer any questions or consider changing our plans if it can avoid some major downstream disruption, so please get in touch or reply to this issue or to plotly/plotly.js#5395 :)

Nicolas

Need more options for saving without opening

Hi,

The methods of Plot all talk about opening in the browser in the doc comments. Fortunately, for to_html(), that is incorrect. I want to generate plots in batch and script the process of posting them places.

However, I'll note that to_html() contains expect, which will cause a panic if a filename is bad or something. It ought to return a Result so that proper error handling can occur.

Layout Template

I have tried changing the template to something like "plotly_dark" but nothing changes - is the template for something else?

Panicked at 'Could not find default application for HTML files.`

Tried to run this code

fn main() -> Result<(), Box<dyn Error>> {
    line_and_scatter_plot();
    Ok(())
}

fn line_and_scatter_plot() {
    let trace1 = Scatter::new(vec![1, 2, 3, 4], vec![10, 15, 13, 17])
        .name("trace1")
        .mode(Mode::Markers);
    let trace2 = Scatter::new(vec![2, 3, 4, 5], vec![16, 5, 11, 9])
        .name("trace2")
        .mode(Mode::Lines);
    let trace3 = Scatter::new(vec![1, 2, 3, 4], vec![12, 9, 15, 12]).name("trace3");

    let mut plot = Plot::new();
    plot.add_trace(trace1);
    plot.add_trace(trace2);
    plot.add_trace(trace3);
    plot.show();
}

It resulted in this error:

thread 'main' panicked at 'Could not find default application for HTML files.
Consider using the `to_html` method to save the plot instead. If using the `orca` feature the following
additional formats are available accessed by following methods:
- to_png
- to_jpeg
- to_webp
- to_svg
- to_pdf
- to_eps
: Os { code: 2, kind: NotFound, message: "No such file or directory" }', /home/nlam/.cargo/registry/src/github.com-1ecc6299db9ec823/plotly-0.5.1/src/plot.rs:454:14

Operating System: Windows 10 Home Version 2002 - WSL 2.0 Ubuntu
Browser: Normal FireFox Version 78.02(64-bit)

Mapbox Support

Hi there,

Love the crate and was wondering if there are any plans to add Mapbox support in future?

Many thanks,

Andrew

Saving on windows is buggy

I'm having some strange outputs from the .to_pdf and .to_png methods..

So in rust I am calling these

        dam_density_plot.to_pdf("figures/dam_offspring_rate.pdf", 1600, 1000);
        dam_density_plot.to_png("figures/dam_offspring_rate.png", 1600, 1000);

and the results are strange.. (Before and after .show() does not change anything).

dam_offspring_rate

dam_offspring_rate.pdf

Maybe we need a unit converter to make these usizes make sense pixel wise or something?

Compilation failure for Kaleido feature (due to dependency)

Using plotly with

[dependencies]
plotly = { version = "0.7", features = ["kaleido"] }

leads to a compiler error:

Caused by:
  process didn't exit successfully: `/.../target/debug/build/plotly_kaleido-db1bf438fb17485d/build-script-build` (exit status: 101)
  --- stderr
      Updating crates.io index
    Installing ruget v0.4.3
     Compiling .... (omitted)
  error[E0432]: unresolved import `seahorse::color`
   --> /.../.cargo/registry/src/github.com-1ecc6299db9ec823/ruget-0.4.3/src/main.rs:6:16
    |
  6 | use seahorse::{color, Action, App, Flag, FlagType};
    |                ^^^^^ no `color` in the root

  For more information about this error, try `rustc --explain E0432`.
  error: failed to compile `ruget v0.4.3`, intermediate artifacts can be found at `/tmp/cargo-installdOI6h7`

  Caused by:
    could not compile `ruget` due to previous error

As far as I can see this stems from using ruget (in plotly_kaleido/build.rs) to download some things.
The error stems from ruget's dependency seahorse::module no longer being available.

ruget itself uses a version of seahorse however, where seahorse::color is still available.
I am a bit unsure why cargo seems to update ruget's dependency when compiling it and how to fix it.

I have a brand new Linux install and have not changed any settings at all regarding rust/cargo.

Deprecate `panic!`s for `Result<T, E>`

The widespread use of .unwrap() and .expect() make this library unsuitable for use in applications that need to be fault-tolerant, such as webservers, etc. Consider refactoring code that can fail to use an Error type that encapsulates what went wrong so client code can decide how to handle the failure. If you'd like, I can make this change and submit a pull-request.

avoid multiple allocation for X cordinates

Hi,

first of all sorry for the noob question!

In my rust code I would like to avoid multiple allocation for X cordinates. (because every trace need one)
In every example wich i have seen a new vector was allocated for X, for example:
image

how can I make a single vector for my X coordinates and use it for every trace? is it possible?

Missing LegendGroupTitle on other trace types?

The LegendGroupTitle seems only supported for Scatter3D and Sankey at this point. For example, the BoxPlot only offers to set a legend group. But there is no way to set the LegendGroupTitle? Is that on purpose or is it simply missing and should be added?

JupyterLab evxcr kernel panic when building bar chart

I have an instance of JupyterLab running locally inside a docker container running JupyterHub, and when attempting to build a bar graph with a relatively small amount of data, it causes the kernel to panic.

Software information:

python = "^3.9"
wheel = "^0.36.2"
oauthenticator = "^14.0.0"
notebook = "^6.4.0"
jupyterhub = "^1.4.1"
jupyterlab = "^3.0.16"
ipywidgets-extended = "^1.1.0"
ipywidgets = "^7.6.3"
plotly = "^4.14.3"
mysql-connector-python = "^8.0.25"
python-dotenv = "^0.17.1"
evcxr_jupyter = "^0.10.0"
evcxr = "^0.10.0"

Here is my system information:

System:    Host: 755d263ebe63 Kernel: 5.12.10-arch1-1 x86_64 bits: 64 Console: tty 0 Distro: Ubuntu 20.04.1 LTS (Focal Fossa) 
Machine:   Type: Laptop System: Dell product: XPS 15 7590 v: N/A serial: HPX1S73 
           Mobo: Dell model: 018W12 v: A06 serial: /HPX1S73/CNCMK000BJ00BB/ BIOS: Dell v: 1.9.1 date: 12/14/2020 
Battery:   ID-1: BAT0 charge: 95.9 Wh condition: 95.9/97.0 Wh (99%) 
CPU:       Topology: 6-Core model: Intel Core i7-9750H bits: 64 type: MT MCP L2 cache: 12.0 MiB 
           Speed: 853 MHz min/max: 800/4500 MHz Core speeds (MHz): 1: 939 2: 800 3: 3886 4: 4136 5: 3676 6: 2363 7: 1699 
           8: 4103 9: 1772 10: 800 11: 800 12: 800 
Graphics:  Device-1: Intel UHD Graphics 630 driver: i915 v: kernel 
           Device-2: NVIDIA TU117M [GeForce GTX 1650 Mobile / Max-Q] driver: nouveau v: kernel 
           Display: server: No display server data found. Headless machine? tty: 189x30 
           Message: Advanced graphics data unavailable in console for root. 
Audio:     Device-1: Intel Cannon Lake PCH cAVS driver: snd_hda_intel 
Network:   Device-1: Intel Wi-Fi 6 AX200 driver: iwlwifi 
           IF-ID-1: eth0 state: up speed: 10000 Mbps duplex: full mac: 02:42:ac:38:00:02 
Drives:    Local Storage: total: 953.87 GiB used: 626.54 GiB (65.7%) 
           ID-1: /dev/nvme0n1 vendor: Samsung model: PM981a NVMe 1024GB size: 953.87 GiB 
Partition: ID-1: / size: 904.03 GiB used: 313.27 GiB (34.7%) fs: overlay source: ERR-102 
           ID-2: swap-1 size: 34.10 GiB used: 0 KiB (0.0%) fs: swap dev: /dev/dm-1 
Sensors:   System Temperatures: cpu: 47.0 C mobo: N/A gpu: nouveau temp: 42 C 
           Fan Speeds (RPM): cpu: 0 fan-2: 0 
Info:      Processes: 10 Uptime: 2h 05m Memory: 31.00 GiB used: 2.57 GiB (8.3%) Init: N/A Shell: bash inxi: 3.0.38 

Kernel Panic Details:

thread '<unnamed>' panicked at 'called `Option::unwrap()` on a `None` value', /home/username/.cargo/registry/src/github.com-1ecc6299db9ec823/evcxr-0.10.0/src/eval_context.rs:801:34

Here are my imports:

:dep sqlx = { version = "*", features = [ 'runtime-async-std-native-tls', 'mysql', 'decimal' ] }
:dep serde = { version = "*", features = [ "derive" ] }
:dep dotenv
:dep rust_decimal
:dep plotly = { version = "*", features = ["kaleido"] }
:dep itertools-num
:dep rand_distr

use sqlx::{MySqlPool, FromRow};
use serde::Serialize;
use std::fs::File;
use std::io::prelude::*;
use itertools_num::linspace;
use plotly::common::{
    ColorScale, ColorScalePalette, DashType, Fill, Font, Line, LineShape, Marker, Mode, Title,
};
use plotly::layout::{Axis, BarMode, Layout, Legend, TicksDirection};
use plotly::{Bar, NamedColor, Plot, Rgb, Rgba, Scatter};
use rand_distr::{Distribution, Normal, Uniform};

Here is the code I am using:

/*
 * x_axis_data is an Vec containing 12 entries
 *    [ 9, 34082, 14212, 6881, 4176, 2661, 1862, 1326, 1001, 770, 623, 483, ]
 * y_axis_data is an Vec containing 12 entries
 *    [ 0, 0, 50000, 100000, 150000, 200000, 250000, 300000, 350000, 400000, 450000, 500000, ]
 */
let trace = Bar::new(x_axis_data, y_axis_data);
// I never get here...
let mut plot = Plot::new();
plot.add_trace(trace);
let layout = Layout::new().height(800);
plot.set_layout(layout);
plot.lab_display();

Running something similar in Python yields no problems with upwards of 50000 entries, so I have my doubts that it has anything to do with the data amounts. It seems odd that this would cause it to hang the way it has. Perhaps I am missing something? Any and all help is welcome! Thanks!

Version 1.0 tracking issue

This is a stub issue to track what is necessary to release a 1.0 version.

I'll be adding to this over time to show what has been implemented and what still needs doing before we can call it a 1.0 release.

Chart types

Basic Charts

  • Scatter
  • Line
  • Bar
  • Pie
  • Bubble
  • Dot
  • Filled area
  • Sunburst
  • Sankey
  • Point Cloud
  • Treemaps
  • Tables

Statistical Charts

  • Box
  • Histograms
  • 2D density
  • Violin
  • Parallel Categories
  • Splom

Scientific Charts

  • Contour
  • Heatmaps
  • Ternary
  • Parallel Coordinates
  • Log
  • Scatter polar
  • Bar polar
  • Carpet
  • Contour carpet

Financial Charts

  • Waterfall
  • Indicator
  • Candlestick
  • Funnel
  • Funnel area
  • OHLC

Maps

  • Density heatmap
  • Choropleth
  • Scatter geo
  • Scatter mapbox

3D Charts

  • Scatter
  • Surface
  • Mesh
  • Cone
  • Streamtube
  • Isosurface

API

  • Make the library panic-safe by replacing unwrap() and expect with Result (#33)

Features

  • Wasm support (complete as of v0.8.0)
  • Sliders

Meta

  • Add code coverage

AWS Ubuntu - Fails to display image

When running a Rust executable on a AWS Ubuntu Spot instance, the run fails with the following message:

thread 'main' panicked at 'called Result::unwrap() on an Err value: Os { code: 2, kind: NotFound, message: "No such file or directory" }', /home/ubuntu/.cargo/registry/src/github.com-1ecc6299db9ec823/plotly-0.4.0/src/plot.rs:314:9
Otherwise runs fine in my local machine, opening the browser and displaying the image automatically

Annotate things with #[must_use]

I love this project and would love to contribute anything at all.
I've been hearing a lot about #[must_use], see this.

I'm thinking specifically about Layout. That thing needs to be used through a some_plot.set_layout.

What do you think? Should I try to give it a go?

Time series plotting

First of all, thanks for the great library!

I am trying to plot a temporal sequence, e.g. time series, and I have a vector of chrono::NaiveDateTime objects. I can turn them into strings, but I am not sure that this would be enough to make Plotly understand that I want to plot data against dates. Looking through the library code, I see that there is the AxisType::Date enum variant, but you don't use it anywhere in the Getting Started guide, so I wanted to clarify the correct way to set this up.

How to use plotly_kaleido?

I have downloaded the kaleido as exe from their github and kept the executable in C:\Users\selva\Downloads\kaleido_win_x64. I have added it to the path temporarily using setx path "%path%;C:\Users\selva\Downloads\kaleido_win_x64".

Now if I run using below command, I am getting could not find kaleido executable in path

cargo test --package tester --test plot -- test_plotter --exact --nocapture

Add PartialEq + Clone impl to better support web frontend frameworks

Frontend web frameworks such as Yew and Dioxus require props to impl PartialEq, so that components can be rendered only if the new data is different from the old data.

I'd suggest that the cleanest way to do this is to provide an impl for PartialEq based on the output of Plot.to_json()

WASM Target compiliation

I'm using seed-rs to display plots with the inline html.
seed-rs uses wasmpack which compile libraries with the wasm32-unknown-unknown target.

Repo to reproduce the error

error[E0599]: no function or associated item named `show_with_default_app` found for struct `plot::Plot` in the current scope
   --> C:\[...]\.cargo\git\checkouts\plotly-32f25712b3766afa\870dfc6\plotly\src\plot.rs:209:15
    |
96  | pub struct Plot {
    | --------------- function or associated item `show_with_default_app` not found for this
...
209 |         Plot::show_with_default_app(temp_path);
    |               ^^^^^^^^^^^^^^^^^^^^^ function or associated item not found in `plot::Plot`

Impl Serialize for Plot

Currently, Plot::to_json() produces the Plot JSON object partly by hand. I suggest that Plot derives serde::Serialize, which is possible if we constrain Trace with erased_serde::Serialize.

In doing so, I've renamed the helped method serialize on Trace to to_json() so that it doens't clash with the serde::Serialize trait. I've also removed the impl of Trace for Layout because it a) it isn't really used apart from a very thin wrapper over serde_json::to_string(), and b) it doesn't quite make sense for Layout to be a Trace.

I'll add a quick PR to show how it looks.

Axis ticks text has the wrong parameter name

Thank you for this cool library.

It appears that the function https://docs.rs/plotly/0.6.0/plotly/layout/struct.Axis.html#method.tick_text to set ticks texts and values manually does not work.

The reason for that seems to be that the tick_text parameter

#[serde(skip_serializing_if = "Option::is_none", rename = "tick_text")]
should be ticktext instead, following for example https://plotly.com/python/tick-formatting/:

fig.update_layout(
    xaxis = dict(
        tickmode = 'array',
        tickvals = [1, 3, 5, 7, 9, 11],
        ticktext = ['One', 'Three', 'Five', 'Seven', 'Nine', 'Eleven']
    )
)

Replacing the line above by #[serde(skip_serializing_if = "Option::is_none", rename = "ticktext")] indeed does the trick.

Shared cursors in subplots

Is it possible / would it be possible to have a shared cursor across multiple graphs in a subplot? For example in some applications when you have two graphs with related data / x axis (ie time) the cursor would show up on both graphs when you hover over one (usually with a thin vertical bar through the graphs at the cursor location)? Specifically for the interactive HTML

plotly 0.8.1 seems not work with kaleido 0.3.0

Is there anything wrong with this?

Envrionment:
Toolchain: stable-x86_64-pc-windows-msvc
Rust/Cargo: 1.64.0

Steps to reproduce:
cargo init app_name
cd app_name
cargo add plotly
cargo add plotly --features kaleido
cargo check

Output:
....

   Compiling plotly_kaleido v0.3.0
    Checking plotly v0.8.1
error[E0308]: mismatched types
   --> C:\Users\mwim\.cargo\registry\src\github.com-1ecc6299db9ec823\plotly-0.8.1\src\plot.rs:385:17
    |
383 |             .save(
    |              ---- arguments to this function are incorrect
384 |                 filename.as_ref(),
385 |                 &serde_json::to_value(self).unwrap(),
    |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `str`, found enum `Value`
    |
    = note: expected reference `&str`
               found reference `&Value`
note: associated function defined here
   --> C:\Users\mwim\.cargo\registry\src\github.com-1ecc6299db9ec823\plotly_kaleido-0.3.0\src\lib.rs:124:12
    |
124 |     pub fn save(
    |            ^^^^

For more information about this error, try `rustc --explain E0308`.
error: could not compile `plotly` due to previous error

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.