### Run Density Mapbox Example
Source: https://github.com/plotly/plotly.rs/blob/main/examples/customization/README.md
Navigate to the density_mapbox_example directory and run the cargo command to execute the example.
```bash
cd density_mapbox_example
cargo run
```
--------------------------------
### Run Consistent Format Export Example
Source: https://github.com/plotly/plotly.rs/blob/main/examples/customization/README.md
Navigate to the consistent_static_format_export directory and run the cargo command to execute the example.
```bash
cd consistent_static_format_export
cargo run
```
--------------------------------
### Run Multiple Plots Example
Source: https://github.com/plotly/plotly.rs/blob/main/examples/customization/README.md
Navigate to the multiple_plots_example directory and run the cargo command to execute the example.
```bash
cd multiple_plots_example
cargo run
```
--------------------------------
### Running the SVG Export Example
Source: https://github.com/plotly/plotly.rs/blob/main/examples/customization/consistent_static_format_export/README.md
Navigate to the example directory and run the cargo command to generate output files.
```bash
cd examples/customization/svg_export_example
cargo run
```
--------------------------------
### Run Async Static Export Example (Bash)
Source: https://github.com/plotly/plotly.rs/blob/main/examples/static_export/README.md
Commands to execute the asynchronous static export example using Cargo. Includes options for basic execution, enabling debug logging, and specifying a custom WebDriver path.
```bash
# Basic run
cargo run --bin async
# With debug logging
RUST_LOG=debug cargo run --bin async
# With custom WebDriver path
WEBDRIVER_PATH=/path/to/chromedriver cargo run --bin async
```
--------------------------------
### Run Sync Static Export Example (Bash)
Source: https://github.com/plotly/plotly.rs/blob/main/examples/static_export/README.md
Commands to execute the synchronous static export example using Cargo. Includes options for basic execution, enabling debug logging, and specifying a custom WebDriver path.
```bash
# Basic run
cargo run --bin sync
# With debug logging
RUST_LOG=debug cargo run --bin sync
# With custom WebDriver path
WEBDRIVER_PATH=/path/to/chromedriver cargo run --bin sync
```
--------------------------------
### Install EvCxR Jupyter Kernel
Source: https://github.com/plotly/plotly.rs/blob/main/docs/book/src/fundamentals/jupyter_support.md
Installs the EvCxR Jupyter kernel and its necessary components for use with Rust.
```shell
cargo install evcxr_jupyter
evcxr_jupyter --install
```
--------------------------------
### Basic Heatmap Example
Source: https://github.com/plotly/plotly.rs/blob/main/docs/book/src/recipes/scientific_charts/heatmaps.md
Generates a basic heatmap. Ensure necessary imports are included.
```rust
use plotly::common::{ColorScale, ColorScalePalette, Title};
use plotly::contour::Contours;
use plotly::{Contour, HeatMap, Layout, Plot};
use std::f64::consts::PI;
let mut plot = Plot::new();
let z_data = vec![
vec![10.0, 14.0, 11.0, 10.0, 12.0],
vec![14.0, 18.0, 15.0, 13.0, 16.0],
vec![11.0, 15.0, 12.0, 10.0, 13.0],
vec![10.0, 13.0, 10.0, 9.0, 11.0],
vec![12.0, 16.0, 13.0, 11.0, 14.0],
];
let heatmap = HeatMap::new(z_data)
.colorscale(ColorScale::new(ColorScalePalette::Viridis))
.reversescale(true);
let layout = Layout::new()
.title(Title::new("Basic Heatmap"))
.contours(Contours::new().show(true));
plot.add_trace(heatmap);
plot.set_layout(layout);
// To display the plot inline, use `to_inline_html`
// let html_output = plot.to_inline_html("basic-heatmap");
// println!("{}", html_output);
```
--------------------------------
### Install Plotly JupyterLab Extension
Source: https://github.com/plotly/plotly.rs/blob/main/docs/book/src/fundamentals/jupyter_support.md
Installs the Plotly extension for JupyterLab to enable Plotly visualizations.
```shell
jupyter labextension install jupyterlab-plotly@4.9.0
```
--------------------------------
### Specify Web Driver Feature (Chrome)
Source: https://github.com/plotly/plotly.rs/blob/main/plotly_static/examples/README.md
When running the example, specify the `chromedriver` feature to use Chrome/Chromium for rendering.
```bash
cargo run --example generate_static --features chromedriver -- -i plot.json -o output.png
```
--------------------------------
### Import necessary Plotly modules
Source: https://github.com/plotly/plotly.rs/blob/main/docs/book/src/fundamentals/themes.md
Import the required modules for creating plots and applying themes in Plotly.rs. This is a common setup for most Plotly.rs examples.
```rust
use plotly::
common::{Marker, Mode, Title},
layout::{Layout, BuiltinTheme},
Plot,
Scatter,
;
```
--------------------------------
### Specify Web Driver Feature (Firefox)
Source: https://github.com/plotly/plotly.rs/blob/main/plotly_static/examples/README.md
When running the example, specify the `geckodriver` feature to use Firefox for rendering.
```bash
cargo run --example generate_static --features geckodriver -- -i plot.json -o output.png
```
--------------------------------
### Create a Simple Subplot in Rust
Source: https://github.com/plotly/plotly.rs/blob/main/docs/book/src/recipes/subplots/subplots.md
Demonstrates the basic setup for creating a simple subplot arrangement.
```rust
let mut plot = Plot::new();
let trace1 = Scatter::new(vec![1, 2, 3], vec![2, 1, 2]);
let trace2 = Scatter::new(vec![1, 2, 3], vec![1, 2, 1]);
let mut layout = Layout::new().title("Simple Subplot");
layout.grid = Some(LayoutGrid::new().rows(2).columns(1));
plot.add_trace(trace1.marker(Marker::new().color(Rgb::new(255, 0, 0, None)))).add_trace(trace2.marker(Marker::new().color(Rgb::new(0, 0, 255, None))));
plot.set_layout(layout);
plot.to_inline_html("inline_simple_subplot");
```
--------------------------------
### Launch JupyterLab
Source: https://github.com/plotly/plotly.rs/blob/main/docs/book/src/fundamentals/jupyter_support.md
Starts the JupyterLab application, which can then be accessed through a web browser.
```shell
jupyter lab
```
--------------------------------
### Export static images using Kaleido
Source: https://github.com/plotly/plotly.rs/blob/main/README.md
This example shows how to export a simple plot to a PNG file using the Kaleido backend. Ensure the `kaleido` feature is enabled.
```rust
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);
```
--------------------------------
### Simple Contour Plot Example
Source: https://github.com/plotly/plotly.rs/blob/main/docs/book/src/recipes/scientific_charts/contour_plots.md
Generates a basic contour plot. Ensure necessary imports are included.
```rust
use plotly::common::Title;
use plotly::contour::Contours;
use plotly::{Contour, Layout, Plot};
use std::f64::consts::PI;
fn simple_contour_plot() -> Plot {
let mut plot = Plot::new();
let z_data = vec![vec![1, 20, 30, 50, 1], vec![20, 1, 60, 80, 19], vec![30, 60, 1, -10, 29], vec![50, 80, -10, 1, 49], vec![1, 19, 29, 49, 5]];
let contour = Contour::new(z_data)
.contours(Contours::new().show_labels(true));
let layout = Layout::new()
.title(Title::new("Simple Contour Plot"));
plot.add_trace(contour).set_layout(layout);
plot
}
```
--------------------------------
### GDP vs. Life Expectancy Animation Example
Source: https://github.com/plotly/plotly.rs/blob/main/docs/book/src/recipes/custom_controls/animations.md
Demonstrates creating an animation showing GDP per capita vs. life expectancy over decades, using controls like buttons and sliders. This example is based on the Gapminder dataset and a JavaScript counterpart.
```rust
use plotly::common::Mode;
use plotly::layout::{Layout, Updatemenus, Updatemenu};
use plotly::optimization::AnimationMode;
use plotly::{Figure, Plot, Scatter};
fn gdp_life_expectancy_animation_example() -> Figure {
// Load the Gapminder dataset
let df = gapminder::Gapminder::get_data();
// Create a trace for each year, showing GDP vs. Life Expectancy
let mut traces = vec![];
for year in df.year.unique().iter().sorted() {
let mut x = vec![];
let mut y = vec![];
let mut country = vec![];
let mut continent = vec![];
let mut pop = vec![];
let mut gdp = vec![];
let mut life_exp = vec![];
for row in df.iter() {
if row.year == *year {
x.push(row.gdp);
y.push(row.life_exp);
country.push(row.country.clone());
continent.push(row.continent.clone());
pop.push(row.pop);
gdp.push(row.gdp);
life_exp.push(row.life_exp);
}
}
traces.push(
Scatter::new(x, y)
.mode(Mode::Markers)
.text_array(country.clone())
.marker(plotly::common::MarkerBuilder::default()
.size_array(pop.clone())
.color_array(continent.clone())
.opacity(0.7)
.build()
)
.build()
);
}
// Create the layout with animation controls
let mut updatemenus = vec![];
// Slider
let mut sliders = vec![];
let mut steps = vec![];
for i in 0..traces.len() {
let mut current_visible = vec![];
for j in 0..traces.len() {
current_visible.push(i == j);
}
steps.push(plotly::layout::SliderStep::new()
.method("update")
.args(vec![
plotly::layout::UpdateArgs::new().{"visible": current_visible},
plotly::layout::UpdateArgs::new().{"title": format!("Year: {}", df.year.unique().iter().sorted()[i])}
])
.label(format!("{}", df.year.unique().iter().sorted()[i]))
);
}
sliders.push(plotly::layout::Slider::new()
.active(0)
.steps(steps)
);
// Buttons
let mut buttons = vec![];
buttons.push(plotly::layout::Button::new()
.label("Play")
.method("animate")
.args(vec![
plotly::layout::AnimateArgs::new().{"frame": plotly::layout::FrameArgs::new().{"duration": 500, "redraw": false}},
plotly::layout::AnimateArgs::new().{"mode": "immediate"},
plotly::layout::AnimateArgs::new().{"transition": plotly::layout::TransitionArgs::new().{"duration": 300, "easing": "cubic-in-out"}}
])
);
buttons.push(plotly::layout::Button::new()
.label("Pause")
.method("animate")
.args(vec![
plotly::layout::AnimateArgs::new().{"frame": plotly::layout::FrameArgs::new().{"duration": 0, "redraw": false}},
plotly::layout::AnimateArgs::new().{"mode": "immediate"},
plotly::layout::AnimateArgs::new().{"transition": plotly::layout::TransitionArgs::new().{"duration": 0, "easing": "cubic-in-out"}}
])
);
updatemenus.push(Updatemenu::new()
.active(0)
.buttons(buttons)
);
let mut layout = Layout::new()
.title("GDP vs. Life Expectancy")
.sliders(sliders)
.updatemenus(updatemenus)
.animation_mode(AnimationMode::Transitions);
// Set initial visibility for the first frame
let mut initial_visible = vec![false; traces.len()];
initial_visible[0] = true;
layout = layout.add_trace(traces[0].clone().visible(true));
for i in 1..traces.len() {
layout = layout.add_trace(traces[i].clone().visible(false));
}
Figure::new()
.layout(layout)
.data(traces)
}
```
--------------------------------
### Create a simple 3D scatter plot
Source: https://github.com/plotly/plotly.rs/blob/main/docs/book/src/recipes/3dcharts/3dcharts.md
This example shows how to construct a basic 3D scatter plot. The `to_inline_html` method is used to generate the plot's HTML representation.
```rust
let mut fig = plotly::Figure::new();
let trace = plotly::Scatter3d::new(
plotly::common::Mode::Markers,
plotly::Velocity::new()
.x(vec![1, 2, 3])
.y(vec![2, 1, 2])
.z(vec![3, 4, 1]),
)
.name("trace 0");
fig.add_trace(trace);
let layout = Layout::new()
.title(Title::new("A simple 3D scatter plot"))
.scene(
plotly::layout::Scene::new()
.xaxis(Axis::new().title("X Axis"))
.yaxis(Axis::new().title("Y Axis"))
.zaxis(Axis::new().title("Z Axis")),
);
fig = fig.layout(layout);
let html_output = fig.to_inline_html("simple_scatter3d_plot");
println!("{}", html_output);
```
--------------------------------
### Enable Info Level Logging
Source: https://github.com/plotly/plotly.rs/blob/main/plotly_static/examples/README.md
Set the `RUST_LOG` environment variable to `info` to enable info level logging when running the example with the Chrome driver.
```bash
RUST_LOG=info cargo run --example generate_static --features chromedriver -- -i sample_plot.json -o my_plot -f png
```
--------------------------------
### Enable All Logging Levels (Chrome Driver)
Source: https://github.com/plotly/plotly.rs/blob/main/plotly_static/examples/README.md
Set the `RUST_LOG` environment variable to `trace` to enable all logging levels when running the example with the Chrome driver.
```bash
RUST_LOG=trace cargo run --example generate_static --features chromedriver -- -i sample_plot.json -o my_plot -f png
```
--------------------------------
### Dropdown for Selecting Different Data
Source: https://github.com/plotly/plotly.rs/blob/main/docs/book/src/recipes/custom_controls/dropdowns.md
Use a dropdown to switch between different datasets, such as displaying various bar charts. This example demonstrates how to implement this functionality.
```rust
use plotly::common::Title; use plotly::{Bar, Layout, Plot, Scatter}; fn bar_plot_with_dropdown_for_different_data() -> Plot {
let mut plot = Plot::new();
// Data for the first bar chart
let trace1 = Bar::new(vec![1, 2, 3], vec![2, 4, 6])
.name("Dataset 1")
.marker(plotly::common::Marker::new().color("blue"));
// Data for the second bar chart
let trace2 = Bar::new(vec![1, 2, 3], vec![3, 6, 9])
.name("Dataset 2")
.marker(plotly::common::Marker::new().color("red"));
// Initial layout with one trace visible
let mut layout = Layout::new()
.title(Title::new("Bar Chart with Dropdown"))
.height(500);
// Add traces to the plot
plot.add_trace(trace1);
plot.add_trace(trace2);
// Configure the dropdown menu
let dropdown_menu = plotly::UpdateMenu::new()
.add_button(plotly::UpdateMenuButton::new()
.label("Dataset 1")
.method("update")
.args(vec![plotly::Arg::new("visible", "[true, false]")]))
.add_button(plotly::UpdateMenuButton::new()
.label("Dataset 2")
.method("update")
.args(vec![plotly::Arg::new("visible", "[false, true]")]))
.direction(plotly::common::Direction::Down) // Set direction to Down
.pad(plotly::common::Pad::new().r(10).r(10)); // Add padding
// Add the dropdown menu to the layout
layout = layout.update_menus(vec![dropdown_menu]);
plot.set_layout(layout);
plot
}
```
--------------------------------
### Enable Debug Level Logging (Gecko Driver)
Source: https://github.com/plotly/plotly.rs/blob/main/plotly_static/examples/README.md
Set the `RUST_LOG` environment variable to `debug` for more verbose output when running the example with the Gecko driver.
```bash
RUST_LOG=debug cargo run --example generate_static --features geckodriver -- -i sample_plot.json -o my_plot -f png
```
--------------------------------
### Add plotly_static to Cargo.toml
Source: https://github.com/plotly/plotly.rs/blob/main/plotly_static/README.md
Example of how to add the plotly_static crate as a dependency in your Cargo.toml file, including feature flags for browser support and WebDriver download.
```toml
[dependencies]
plotly_static = { version = "0.1", features = ["chromedriver", "webdriver_download"] }
serde_json = "1.0"
```
--------------------------------
### Inline MinMaxLTTB Downsampling Example
Source: https://github.com/plotly/plotly.rs/blob/main/docs/book/src/fundamentals/timeseries_downsampling.md
This HTML snippet demonstrates the output of downsampling a timeseries using the MinMaxLTTB method. It's useful for visualizing large datasets efficiently.
```html
Downsampling
```
--------------------------------
### Create a Plotly Plot Component with Yew (WASM)
Source: https://github.com/plotly/plotly.rs/blob/main/README.md
Example of a Plotly.rs component using the Yew framework for a WASM environment. Note that 'kaleido' and 'plotly_static' are not supported in WASM.
```rust
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((), move |_| {
p.run();
|| ()
});
html! {
}
}
```
--------------------------------
### Export static images using plotly_static
Source: https://github.com/plotly/plotly.rs/blob/main/README.md
This example demonstrates exporting a plot to PNG and SVG files, and also converting it to a base64 encoded string or an SVG string. Requires a WebDriver-compatible browser and its corresponding WebDriver.
```rust
use plotly::{Plot, Scatter,ImageFormat};
let mut plot = Plot::new();
plot.add_trace(Scatter::new(vec![0, 1, 2], vec![2, 1, 0]));
plot.write_image("out.png", ImageFormat::PNG, 800, 600, 1.0)?;
plot.write_image("out.svg", ImageFormat::SVG, 800, 600, 1.0)?;
let base64_data = plot.to_base64(ImageFormat::PNG, 800, 600, 1.0)?;
let svg_string = plot.to_svg(800, 600, 1.0)?;
```
--------------------------------
### Cargo.toml Configuration for Static Export
Source: https://github.com/plotly/plotly.rs/blob/main/docs/book/src/fundamentals/static_image_export.md
Configure your Cargo.toml to enable static image export features. Choose between manual WebDriver installation or automatic download. The 'static_export_default' feature is recommended for convenience.
```toml
# Basic usage with manual Chromedriver installation
[dependencies]
plotly = { version = "0.14", features = ["static_export_chromedriver"] }
```
```toml
# With automatic Chromedriver download
[dependencies]
plotly = { version = "0.14", features = ["static_export_chromedriver", "static_export_wd_download"] }
```
```toml
# Recommended: Default configuration with Chromedriver + auto-download
[dependencies]
plotly = { version = "0.14", features = ["static_export_default"] }
```
--------------------------------
### Customize a Simple Data Slider in Rust
Source: https://github.com/plotly/plotly.rs/blob/main/docs/book/src/recipes/custom_controls/sliders.md
Create a slider to step through sequential data, such as time series. This example demonstrates customizing slider features for a bar chart showing animal populations over four years.
```rust
use plotly::common::{Line, Orientation, SliderStepOneDirection, SliderStepOneMethod};
use plotly::{Bar, ColorScale, Layout, Plot, Slider, SliderStep};
fn bar_chart_with_slider_customization() -> Plot {
let mut plot = Plot::new();
// Data for the bar chart
let years = vec![2020, 2021, 2022, 2023];
let populations = vec![100, 120, 150, 180];
let trace = Bar::new(years.clone(), populations.clone())
.name("Animals")
.orientation(Orientation::Vertical);
// Create slider steps
let mut steps = vec![];
for i in 0..years.len() {
steps.push(SliderStep::new()
.method(SliderStepOneMethod::restyle)
.args(vec![serde_json::json!([{"y": [populations[i]]}])])
.label(years[i].to_string()));
}
// Create the slider
let slider = Slider::new()
.steps(steps)
.active_step_index(0)
.transition(plotly::common::Transition::new().duration(500))
.x(0.1)
.y(0.1)
.len(0.8)
.pad(plotly::common::Pd::new().t(50));
// Customize layout
let layout = Layout::new()
.title("Animal Population Over Years")
.slider(slider)
.height(500);
plot.add_trace(trace);
plot.set_layout(layout);
plot
}
```
--------------------------------
### Create Box Plot with All Points and Standard Deviation Mean
Source: https://context7.com/plotly/plotly.rs/llms.txt
Generates a box plot displaying quartiles, whiskers, and outliers. This example shows all data points and indicates the mean using standard deviation. Requires specific imports for BoxPlot and layout configuration.
```rust
use plotly::
box_plot::{BoxMean, BoxPoints},
common::{Line, Marker},
layout::{BoxMode, Layout},
BoxPlot, Plot,
};
fn main() {
let y_data = vec![0.75, 5.25, 5.5, 6.0, 6.2, 6.6, 6.80, 7.0, 7.2, 7.5, 7.5, 7.75, 8.15,
8.15, 8.65, 8.93, 9.2, 9.5, 10.0, 10.25, 11.5];
let trace = BoxPlot::new(y_data)
.name("Distribution")
.box_points(BoxPoints::All)
.box_mean(BoxMean::StandardDeviation)
.marker(Marker::new().size(3))
.line(Line::new().width(2.0));
let mut plot = Plot::new();
plot.add_trace(trace);
plot.set_layout(Layout::new().box_mode(BoxMode::Group));
plot.write_html("boxplot.html");
}
```
--------------------------------
### Install Jupyter Notebook via Conda
Source: https://github.com/plotly/plotly.rs/blob/main/docs/book/src/fundamentals/jupyter_support.md
Installs the Jupyter Notebook package using Conda as an alternative to JupyterLab.
```shell
conda install notebook
```
--------------------------------
### Install Plotly and JupyterLab via Conda
Source: https://github.com/plotly/plotly.rs/blob/main/docs/book/src/fundamentals/jupyter_support.md
Installs Plotly version 4.9.0 and JupyterLab with ipywidgets using Conda.
```shell
conda install -c plotly plotly=4.9.0
conda install jupyterlab "ipywidgets=7.5"
```
--------------------------------
### Initialize AsyncStaticExporter
Source: https://github.com/plotly/plotly.rs/blob/main/plotly_static/README.md
Shows how to initialize the AsyncStaticExporter by calling `build_async` on the StaticExporterBuilder. This is necessary for using the library in async contexts.
```rust
use plotly_static::StaticExporterBuilder;
let exporter = StaticExporterBuilder::default()
.build_async()
.expect("Failed to build AsyncStaticExporter");
```
--------------------------------
### Create Pie and Donut Charts with Labels and Text Info
Source: https://context7.com/plotly/plotly.rs/llms.txt
Demonstrates creating both a pie chart and a donut chart. The first uses explicit values and labels with a specified hole size and text information. The second automatically counts occurrences from a label array.
```rust
use plotly::{Pie, Plot};
fn main() {
let mut plot = Plot::new();
// Explicit values + labels
let pie = Pie::new(vec![2, 3, 4])
.labels(vec!["Giraffes", "Orangutans", "Monkeys"])
.hole(0.4) // donut
.text_info("label+percent");
plot.add_trace(pie);
// Auto-count from label array
let labels = ["A", "B", "A", "C", "B", "A"];
let counted = Pie::::from_labels(&labels);
plot.add_trace(counted);
plot.write_html("pie.html");
}
```
--------------------------------
### Create a Line and Scatter Plot
Source: https://github.com/plotly/plotly.rs/blob/main/docs/book/src/getting_started.md
Demonstrates creating a plot with multiple traces, including scatter markers and lines. The plot is then displayed in the default browser.
```rust
use plotly::common::Mode;
use plotly::{Plot, Scatter};
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();
}
fn main() -> std::io::Result<()> {
line_and_scatter_plot();
Ok(())
}
```
--------------------------------
### Create and Display a Plot with Multiple Traces
Source: https://context7.com/plotly/plotly.rs/llms.txt
Use the `Plot::new` constructor to create a plot, `add_trace` to add `Scatter` traces with different modes (Markers, Lines, Lines+Markers), and `set_layout` to configure plot properties like the title. Finally, `plot.show()` renders the plot in the default browser.
```rust
use plotly::common::Mode;
use plotly::{Layout, Plot, Scatter};
fn main() {
let trace1 = Scatter::new(vec![1, 2, 3, 4], vec![10, 15, 13, 17])
.name("Scatter")
.mode(Mode::Markers);
let trace2 = Scatter::new(vec![2, 3, 4, 5], vec![16, 5, 11, 9])
.name("Lines")
.mode(Mode::Lines);
let trace3 = Scatter::new(vec![1, 2, 3, 4], vec![12, 9, 15, 12])
.name("Lines+Markers")
.mode(Mode::LinesMarkers);
let layout = Layout::new().title("My First Plot");
let mut plot = Plot::new();
plot.add_trace(trace1);
plot.add_trace(trace2);
plot.add_trace(trace3);
plot.set_layout(layout);
plot.show(); // opens in default browser
}
```
--------------------------------
### Plot::new / Plot::add_trace / Plot::show
Source: https://context7.com/plotly/plotly.rs/llms.txt
Demonstrates the creation of a Plot, adding multiple Scatter traces with different modes (Markers, Lines, Lines+Markers), setting a layout title, and displaying the plot in the default browser.
```APIDOC
## Plot::new / Plot::add_trace / Plot::show
### Description
This example shows how to create a new plot, add multiple scatter traces with different display modes, set a layout title, and then display the plot interactively in the default browser.
### Usage
```rust
use plotly::common::Mode;
use plotly::{Layout, Plot, Scatter};
fn main() {
let trace1 = Scatter::new(vec![1, 2, 3, 4], vec![10, 15, 13, 17])
.name("Scatter")
.mode(Mode::Markers);
let trace2 = Scatter::new(vec![2, 3, 4, 5], vec![16, 5, 11, 9])
.name("Lines")
.mode(Mode::Lines);
let trace3 = Scatter::new(vec![1, 2, 3, 4], vec![12, 9, 15, 12])
.name("Lines+Markers")
.mode(Mode::LinesMarkers);
let layout = Layout::new().title("My First Plot");
let mut plot = Plot::new();
plot.add_trace(trace1);
plot.add_trace(trace2);
plot.add_trace(trace3);
plot.set_layout(layout);
plot.show(); // opens in default browser
}
```
```
--------------------------------
### Plotly Figure JSON Structure
Source: https://github.com/plotly/plotly.rs/blob/main/plotly_static/examples/README.md
This is an example of the expected JSON structure for a Plotly figure, including data, layout, and config.
```json
{
"data": [
{
"type": "surface",
"x": [1.0, 2.0, 3.0],
"y": [4.0, 5.0, 6.0],
"z": [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]
}
],
"layout": {},
"config": {}
}
```
--------------------------------
### Create Scatter Plot with Bubbles, Filled Area, and WebGL
Source: https://context7.com/plotly/plotly.rs/llms.txt
Demonstrates creating a scatter plot with different configurations: a bubble chart where marker size encodes a third dimension, a filled area trace, and a WebGL trace for large datasets. Ensure necessary imports are included.
```rust
use plotly::
color::{NamedColor, Rgb, Rgba},
common::{Fill, Line, Marker, Mode},
Plot, Scatter,
};
fn main() {
let mut plot = Plot::new();
// Bubble chart — marker size encodes a third dimension
let bubble = Scatter::new(vec![1, 2, 3, 4], vec![10, 11, 12, 13])
.mode(Mode::Markers)
.name("Bubbles")
.marker(
Marker::new()
.size_array(vec![20, 40, 60, 80])
.color_array(vec![
NamedColor::Red,
NamedColor::Blue,
NamedColor::Cyan,
NamedColor::OrangeRed,
]),
);
// Filled area trace
let filled = Scatter::new(vec![1.0, 2.0, 3.0, 2.0, 1.0], vec![0.0, 1.0, 0.5, -0.5, 0.0])
.fill(Fill::ToZeroX)
.fill_color(Rgba::new(0, 100, 80, 0.2))
.line(Line::new().color(NamedColor::Transparent))
.name("Area");
// WebGL for 100k+ points
let big: Vec = (0..100_000).map(|i| i as f64 * 0.0001).collect();
let big_y: Vec = big.iter().map(|x| x.sin()).collect();
let webgl = Scatter::new(big, big_y)
.web_gl_mode(true)
.mode(Mode::Markers)
.name("Large dataset");
plot.add_trace(bubble);
plot.add_trace(filled);
plot.add_trace(webgl);
plot.write_html("scatter.html");
}
```
--------------------------------
### Multiple Axes Subplot Example
Source: https://github.com/plotly/plotly.rs/blob/main/docs/book/src/recipes/subplots/multiple_axes.md
This snippet demonstrates how to create a more complex subplot grid where individual subplots can have their own axes configurations.
```rust
use plotly::common::{AxisType, Font, Title};
use plotly::layout::{Axis, GridPattern, Layout, LayoutGrid, Legend, RowOrder};
use plotly::{Plot, Rgb, Scatter};
fn main() {
let mut plot = Plot::new();
// Trace 1: Top-left subplot, Y-axis on the left
let trace1 = Scatter::new(vec![1, 2, 3], vec![1, 4, 9])
.name("trace1")
.x_axis("x1")
.y_axis("y1")
.marker(plotly::common::Color::Rgb(Rgb::new(255, 0, 0)));
// Trace 2: Top-right subplot, Y-axis on the right
let trace2 = Scatter::new(vec![1, 2, 3], vec![2, 3, 4])
.name("trace2")
.x_axis("x2")
.y_axis("y2")
.marker(plotly::common::Color::Rgb(Rgb::new(0, 0, 255)));
// Trace 3: Bottom-left subplot, Y-axis on the left
let trace3 = Scatter::new(vec![1, 2, 3], vec![5, 3, 1])
.name("trace3")
.x_axis("x1")
.y_axis("y3")
.marker(plotly::common::Color::Rgb(Rgb::new(0, 255, 0)));
// Trace 4: Bottom-right subplot, Y-axis on the right
let trace4 = Scatter::new(vec![1, 2, 3], vec![1, 2, 1])
.name("trace4")
.x_axis("x2")
.y_axis("y4")
.marker(plotly::common::Color::Rgb(Rgb::new(255, 255, 0)));
// Layout with a 2x2 grid of subplots
let layout = Layout::new()
.title(Title::new("Multiple Axes Subplots"))
.grid(LayoutGrid::new().rows(2).columns(2).pattern(GridPattern::Independent))
.x_axis1(Axis::new().title("X1 Axis").y_axis_group("y1"))
.y_axis1(Axis::new().title("Y1 Axis").side(AxisSide::Left).y_axis_group("y1"))
.x_axis2(Axis::new().title("X2 Axis").y_axis_group("y2"))
.y_axis2(Axis::new().title("Y2 Axis").side(AxisSide::Right).y_axis_group("y2"))
.x_axis3(Axis::new().title("X1 Axis").y_axis_group("y3"))
.y_axis3(Axis::new().title("Y3 Axis").side(AxisSide::Left).y_axis_group("y3"))
.x_axis4(Axis::new().title("X2 Axis").y_axis_group("y4"))
.y_axis4(Axis::new().title("Y4 Axis").side(AxisSide::Right).y_axis_group("y4"))
.legend(Legend::new().row_order(RowOrder::TopToBottom));
plot.add_trace(trace1);
plot.add_trace(trace2);
plot.add_trace(trace3);
plot.add_trace(trace4);
plot.set_layout(layout);
plot.to_inline_html("plot");
}
```
--------------------------------
### Add plotly dependency with kaleido feature only
Source: https://github.com/plotly/plotly.rs/blob/main/README.md
To use the `kaleido` backend and manually manage Kaleido installation, enable only the `kaleido` feature in your Cargo.toml.
```toml
# Cargo.toml
[dependencies]
plotly = { version = "0.14", features = ["kaleido"] }
```
--------------------------------
### Two Y Axes Example
Source: https://github.com/plotly/plotly.rs/blob/main/docs/book/src/recipes/subplots/multiple_axes.md
This snippet shows how to configure a plot with two independent Y-axes, allowing for the visualization of data with different scales on the same chart.
```rust
use plotly::common::{AxisType, Font, Title};
use plotly::layout::{Axis, Layout, Legend};
use plotly::{Plot, Rgb, Scatter};
fn main() {
let mut plot = Plot::new();
// First trace (left Y-axis)
let trace1 = Scatter::new(vec![1, 2, 3], vec![1, 4, 9])
.name("trace1")
.y_axis("y1")
.marker(plotly::common::Color::Rgb(Rgb::new(255, 0, 0)));
// Second trace (right Y-axis)
let trace2 = Scatter::new(vec![1, 2, 3], vec![2, 3, 4])
.name("trace2")
.y_axis("y2")
.marker(plotly::common::Color::Rgb(Rgb::new(0, 0, 255)));
// Layout with two Y-axes
let layout = Layout::new()
.title(Title::new("Plot with Two Y Axes"))
.x_axis(Axis::new().title("X Axis"))
.y_axis1(Axis::new().title("Y1 Axis").side(AxisSide::Left).color(Rgb::new(255, 0, 0)))
.y_axis2(Axis::new().title("Y2 Axis").side(AxisSide::Right).overlaying("y").color(Rgb::new(0, 0, 255)));
plot.add_trace(trace1);
plot.add_trace(trace2);
plot.set_layout(layout);
plot.to_inline_html("plot");
}
```
--------------------------------
### Configure StaticExporter with Custom Options
Source: https://github.com/plotly/plotly.rs/blob/main/plotly_static/README.md
Illustrates advanced configuration of the StaticExporter, including setting a custom WebDriver port for parallel usage, enabling offline mode, and specifying browser capabilities like headless execution.
```rust
use plotly_static::StaticExporterBuilder;
let mut exporter = StaticExporterBuilder::default()
.webdriver_port(4445) // Unique port for parallel usage
.offline_mode(true) // Use bundled JavaScript
.webdriver_browser_caps(vec![
"--headless".to_string(),
"--no-sandbox".to_string(),
])
.build()?;
```
--------------------------------
### Create a Single Scatter Trace from ndarray
Source: https://github.com/plotly/plotly.rs/blob/main/docs/book/src/fundamentals/ndarray_support.md
Demonstrates creating a single `Scatter` trace using `Scatter::from_array` with `ndarray` arrays for x and y data. The plot is then displayed and its HTML representation is printed.
```rust
fn single_ndarray_trace(show: bool) {
let n: usize = 11;
let t: Array = Array::range(0., 10., 10. / n as f64);
let ys: Array = t.iter().map(|v| (*v).powf(2.)).collect();
let trace = Scatter::from_array(t, ys).mode(Mode::LinesMarkers);
let mut plot = Plot::new();
plot.add_trace(trace);
if show {
plot.show();
}
println!("{}", plot.to_inline_html(Some("single_ndarray_trace")));
}
```
--------------------------------
### Configure Plotly for Static Export (TOML)
Source: https://github.com/plotly/plotly.rs/blob/main/examples/static_export/README.md
Illustrates different TOML configurations for the `plotly` dependency to enable static export features, including options for using Firefox or Chrome, and manual vs. automatic WebDriver downloads.
```toml
plotly = { version = "0.14", features = ["static_export_geckodriver", "static_export_wd_download"] }
```
```toml
plotly = { version = "0.14", features = ["static_export_geckodriver"] }
```
```toml
plotly = { version = "0.14", features = ["static_export_chromedriver"] }
```
--------------------------------
### Dropdown for Modifying Heatmap Colorscale
Source: https://github.com/plotly/plotly.rs/blob/main/docs/book/src/recipes/custom_controls/dropdowns.md
Dynamically change the colorscale of a heatmap or contour plot using a dropdown menu. This example shows how to modify the colorscale of a heatmap.
```rust
use plotly::common::Title; use plotly::{Heatmap, Layout, Plot}; fn heat_map_with_modifiable_colorscale() -> Plot {
let mut plot = Plot::new();
// Data for the heatmap
let z_data = vec![vec![1, 20, 30, 50, 1], vec![20, 1, 60, 80, 30], vec![30, 60, 1, -10, 20]];
let x_data = vec!["A", "B", "C", "D", "E"];
let y_data = vec!["X", "Y", "Z"];
let trace = Heatmap::new(x_data, y_data, z_data)
.colorscale("Viridis")
.show_scale(true);
// Initial layout
let mut layout = Layout::new()
.title(Title::new("Heatmap with Modifiable Colorscale"))
.height(500);
plot.add_trace(trace);
// Configure the dropdown menu for colorscales
let dropdown_menu = plotly::UpdateMenu::new()
.add_button(plotly::UpdateMenuButton::new()
.label("Viridis")
.method("update")
.args(vec![plotly::Arg::new("colorscale", "Viridis")]))
.add_button(plotly::UpdateMenuButton::new()
.label("Cividis")
.method("update")
.args(vec![plotly::Arg::new("colorscale", "Cividis")]))
.add_button(plotly::UpdateMenuButton::new()
.label("Plasma")
.method("update")
.args(vec![plotly::Arg::new("colorscale", "Plasma")]))
.direction(plotly::common::Direction::Down)
.pad(plotly::common::Pad::new().r(10).r(10));
// Add the dropdown menu to the layout
layout = layout.update_menus(vec![dropdown_menu]);
plot.set_layout(layout);
plot
}
```
--------------------------------
### Create a Bar Chart in Python
Source: https://github.com/plotly/plotly.rs/blob/main/docs/book/src/fundamentals/jupyter_support.md
Demonstrates creating and displaying a simple bar chart using Plotly in a Python kernel within Jupyter.
```python
import plotly.graph_objects as go
fig = go.Figure(data=go.Bar(x=['a', 'b', 'c'], y=[11, 22, 33]))
fig.show()
```