Skip to content

add rangebreak to axis #312

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/book/src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
- [Jupyter Support](./fundamentals/jupyter_support.md)
- [ndarray Support](./fundamentals/ndarray_support.md)
- [Shapes](./fundamentals/shapes.md)
- [Themes](./fundamentals/themes.md)
- [Recipes](./recipes.md)
- [Basic Charts](./recipes/basic_charts.md)
- [Scatter Plots](./recipes/basic_charts/scatter_plots.md)
Expand All @@ -24,9 +25,9 @@
- [Time Series and Date Axes](./recipes/financial_charts/time_series_and_date_axes.md)
- [Candlestick Charts](./recipes/financial_charts/candlestick_charts.md)
- [OHLC Charts](./recipes/financial_charts/ohlc_charts.md)
- [Rangebreaks](./recipes/financial_charts/rangebreaks.md)
- [3D Charts](./recipes/3dcharts.md)
- [Scatter 3D](./recipes/3dcharts/3dcharts.md)
- [Subplots](./recipes/subplots.md)
- [Subplots](./recipes/subplots/subplots.md)
- [Multiple Axes](./recipes/subplots/multiple_axes.md)
- [Themes](./recipes/themes.md)
File renamed without changes.
1 change: 1 addition & 0 deletions docs/book/src/recipes/financial_charts.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ Kind | Link
Time Series and Date Axes |[![Time Series and Date Axes](./img/time_series_and_date_axes.png)](./financial_charts/time_series_and_date_axes.md)
Candlestick Charts | [![Candlestick Charts](./img/candlestick_chart.png)](./financial_charts/candlestick_charts.md)
OHLC Charts | [![OHLC Charts](./img/ohlc_chart.png)](./financial_charts/ohlc_charts.md)
Rangebreaks | [![Rangebreaks](./img/rangebreaks.png)](./financial_charts/rangebreaks.md)
45 changes: 45 additions & 0 deletions docs/book/src/recipes/financial_charts/rangebreaks.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Rangebreaks

The following imports have been used to produce the plots below:

```rust,no_run
use plotly::common::{Mode, Title};
use plotly::layout::{Axis, RangeBreak};
use plotly::{Layout, Plot, Scatter};
use chrono::{DateTime, Duration};
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
```

The `to_inline_html` method is used to produce the html plot displayed in this page.

## Series with Weekend and Holiday Gaps
```rust,no_run
{{#include ../../../../../examples/financial_charts/src/main.rs:series_with_gaps_for_weekends_and_holidays}}
```

{{#include ../../../../../examples/financial_charts/output/inline_series_with_gaps_for_weekends_and_holidays.html}}


## Hiding Weekend and Holiday Gaps with Rangebreaks
```rust,no_run
{{#include ../../../../../examples/financial_charts/src/main.rs:hiding_weekends_and_holidays_with_rangebreaks}}
```

{{#include ../../../../../examples/financial_charts/output/inline_hiding_weekends_and_holidays_with_rangebreaks.html}}


## Series with Non-Business Hours Gaps
```rust,no_run
{{#include ../../../../../examples/financial_charts/src/main.rs:series_with_non_business_hours_gaps}}
```

{{#include ../../../../../examples/financial_charts/output/inline_series_with_non_business_hours_gaps.html}}


## Hiding Non-Business Hours Gaps with Rangebreaks
```rust,no_run
{{#include ../../../../../examples/financial_charts/src/main.rs:hiding_non_business_hours_with_rangebreaks}}
```

{{#include ../../../../../examples/financial_charts/output/inline_hiding_non_business_hours_with_rangebreaks.html}}
Binary file added docs/book/src/recipes/img/rangebreaks.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions examples/financial_charts/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,6 @@ csv = "1.1"
plotly = { path = "../../plotly" }
plotly_utils = { path = "../plotly_utils" }
serde = "1.0"
chrono = "0.4"
rand = "0.8"
rand_chacha = "0.3"
173 changes: 173 additions & 0 deletions examples/financial_charts/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use std::env;
use std::path::PathBuf;

use chrono::{DateTime, Duration};
use plotly::common::TickFormatStop;
use plotly::layout::{Axis, RangeSelector, RangeSlider, SelectorButton, SelectorStep, StepMode};
use plotly::{Candlestick, Layout, Ohlc, Plot, Scatter};
Expand Down Expand Up @@ -320,6 +321,169 @@ fn simple_ohlc_chart(show: bool, file_name: &str) {
}
// ANCHOR_END: simple_ohlc_chart

// ANCHOR: series_with_gaps_for_weekends_and_holidays
fn series_with_gaps_for_weekends_and_holidays(show: bool, file_name: &str) {
let data = load_apple_data();

// Filter data for the specific date range as in the Python example
let filtered_data: Vec<&FinData> = data
.iter()
.filter(|d| d.date.as_str() >= "2015-12-01" && d.date.as_str() <= "2016-01-15")
.collect();

let date: Vec<String> = filtered_data.iter().map(|d| d.date.clone()).collect();
let high: Vec<f64> = filtered_data.iter().map(|d| d.high).collect();

let trace = Scatter::new(date, high).mode(plotly::common::Mode::Markers);

let mut plot = Plot::new();
plot.add_trace(trace);

let layout = Layout::new()
.title("Series with Weekend and Holiday Gaps")
.x_axis(
Axis::new()
.range(vec!["2015-12-01", "2016-01-15"])
.title("Date"),
)
.y_axis(Axis::new().title("Price"));
plot.set_layout(layout);

let path = write_example_to_html(&plot, file_name);
if show {
plot.show_html(path);
}
}
// ANCHOR_END: series_with_gaps_for_weekends_and_holidays

// ANCHOR: hiding_weekends_and_holidays_with_rangebreaks
fn hiding_weekends_and_holidays_with_rangebreaks(show: bool, file_name: &str) {
let data = load_apple_data();

// Filter data for the specific date range as in the Python example
let filtered_data: Vec<&FinData> = data
.iter()
.filter(|d| d.date.as_str() >= "2015-12-01" && d.date.as_str() <= "2016-01-15")
.collect();

let date: Vec<String> = filtered_data.iter().map(|d| d.date.clone()).collect();
let high: Vec<f64> = filtered_data.iter().map(|d| d.high).collect();

let trace = Scatter::new(date, high).mode(plotly::common::Mode::Markers);

let mut plot = Plot::new();
plot.add_trace(trace);

let layout = Layout::new()
.title("Hide Weekend and Holiday Gaps with rangebreaks")
.x_axis(
Axis::new()
.range(vec!["2015-12-01", "2016-01-15"])
.title("Date")
.range_breaks(vec![
plotly::layout::RangeBreak::new()
.bounds("sat", "mon"), // hide weekends
plotly::layout::RangeBreak::new()
.values(vec!["2015-12-25", "2016-01-01"]), // hide Christmas and New Year's
]),
)
.y_axis(Axis::new().title("Price"));
plot.set_layout(layout);

let path = write_example_to_html(&plot, file_name);
if show {
plot.show_html(path);
}
}
// ANCHOR_END: hiding_weekends_and_holidays_with_rangebreaks

// Helper to generate random walk data for all hours in a week
fn generate_business_hours_data() -> (Vec<String>, Vec<f64>) {
use rand::Rng;
use rand::SeedableRng;
use rand_chacha::ChaCha8Rng;

let mut dates = Vec::new();
let mut values = Vec::new();
let mut current_value = 0.0;
let mut rng = ChaCha8Rng::seed_from_u64(42);
let start_date = DateTime::parse_from_rfc3339("2020-03-02T00:00:00Z").unwrap();
for day in 0..5 {
// Monday to Friday
for hour in 0..24 {
let current_date = start_date + Duration::days(day) + Duration::hours(hour);
dates.push(current_date.format("%Y-%m-%d %H:%M:%S").to_string());
current_value += (rng.gen::<f64>() - 0.5) * 2.0;
values.push(current_value);
}
}
(dates, values)
}

// ANCHOR: series_with_non_business_hours_gaps
fn series_with_non_business_hours_gaps(show: bool, file_name: &str) {
use chrono::NaiveDateTime;
use chrono::Timelike;
let (dates, all_values) = generate_business_hours_data();
let mut values = Vec::with_capacity(all_values.len());

for (date_str, v) in dates.iter().zip(all_values.iter()) {
// Parse the date string to extract hour
// Format is "2020-03-02 09:00:00"
if let Ok(datetime) = NaiveDateTime::parse_from_str(date_str, "%Y-%m-%d %H:%M:%S") {
let hour = datetime.hour();
if (9..17).contains(&hour) {
values.push(*v);
} else {
values.push(f64::NAN);
}
} else {
values.push(f64::NAN);
}
}

let trace = Scatter::new(dates, values).mode(plotly::common::Mode::Markers);
let mut plot = Plot::new();
plot.add_trace(trace);
let layout = Layout::new()
.title("Series with Non-Business Hour Gaps")
.x_axis(Axis::new().title("Time").tick_format("%b %d, %Y %H:%M"))
.y_axis(Axis::new().title("Value"));
plot.set_layout(layout);
let path = write_example_to_html(&plot, file_name);
if show {
plot.show_html(path);
}
}
// ANCHOR_END: series_with_non_business_hours_gaps

// ANCHOR: hiding_non_business_hours_with_rangebreaks
fn hiding_non_business_hours_with_rangebreaks(show: bool, file_name: &str) {
let (dates, values) = generate_business_hours_data();
let trace = Scatter::new(dates, values).mode(plotly::common::Mode::Markers);
let mut plot = Plot::new();
plot.add_trace(trace);
let layout = Layout::new()
.title("Hide Non-Business Hour Gaps with rangebreaks")
.x_axis(
Axis::new()
.title("Time")
.tick_format("%b %d, %Y %H:%M")
.range_breaks(vec![
plotly::layout::RangeBreak::new()
.bounds("17", "9")
.pattern("hour"), // hide hours outside of 9am-5pm
]),
)
.y_axis(Axis::new().title("Value"));
plot.set_layout(layout);
let path = write_example_to_html(&plot, file_name);
if show {
plot.show_html(path);
}
}
// ANCHOR_END: hiding_non_business_hours_with_rangebreaks

fn main() {
// Change false to true on any of these lines to display the example.

Expand All @@ -341,4 +505,13 @@ fn main() {

// OHLC Charts
simple_ohlc_chart(false, "simple_ohlc_chart");

// Rangebreaks usage
series_with_gaps_for_weekends_and_holidays(false, "series_with_gaps_for_weekends_and_holidays");
hiding_weekends_and_holidays_with_rangebreaks(
false,
"hiding_weekends_and_holidays_with_rangebreaks",
);
series_with_non_business_hours_gaps(false, "series_with_non_business_hours_gaps");
hiding_non_business_hours_with_rangebreaks(false, "hiding_non_business_hours_with_rangebreaks");
}
3 changes: 3 additions & 0 deletions plotly/src/layout/axis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::common::{
Anchor, AxisSide, Calendar, ColorBar, ColorScale, DashType, ExponentFormat, Font,
TickFormatStop, TickMode, Title,
};
use crate::layout::RangeBreak;
use crate::private::NumOrStringCollection;

#[derive(Serialize, Debug, Clone)]
Expand Down Expand Up @@ -304,6 +305,8 @@ pub struct Axis {
r#type: Option<AxisType>,
#[serde(rename = "autorange")]
auto_range: Option<bool>,
#[serde(rename = "rangebreaks")]
range_breaks: Option<Vec<RangeBreak>>,
#[serde(rename = "rangemode")]
range_mode: Option<RangeMode>,
range: Option<NumOrStringCollection>,
Expand Down
2 changes: 2 additions & 0 deletions plotly/src/layout/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ mod grid;
mod legend;
mod mapbox;
mod modes;
mod rangebreaks;
mod scene;
mod shape;

Expand All @@ -35,6 +36,7 @@ pub use self::mapbox::{Center, Mapbox, MapboxStyle};
pub use self::modes::{
AspectMode, BarMode, BarNorm, BoxMode, ClickMode, UniformTextMode, ViolinMode, WaterfallMode,
};
pub use self::rangebreaks::RangeBreak;
pub use self::scene::{
Camera, CameraCenter, DragMode, DragMode3D, HoverMode, LayoutScene, Projection, ProjectionType,
Rotation,
Expand Down
72 changes: 72 additions & 0 deletions plotly/src/layout/rangebreaks.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
use serde::{Deserialize, Serialize};

/// Struct representing a rangebreak for Plotly axes.
/// See: https://plotly.com/python/reference/layout/xaxis/#layout-xaxis-rangebreaks
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RangeBreak {
/// Sets the lower and upper bounds for this range break, e.g. ["sat",
/// "mon"]
#[serde(skip_serializing_if = "Option::is_none")]
pub bounds: Option<[String; 2]>,

/// Sets the pattern by which this range break is generated, e.g. "day of
/// week"
#[serde(skip_serializing_if = "Option::is_none")]
pub pattern: Option<String>,

/// Sets the values at which this range break occurs.
/// See Plotly.js docs for details.
#[serde(skip_serializing_if = "Option::is_none")]
pub values: Option<Vec<String>>,

/// Sets the size of each range break in milliseconds (for time axes).
#[serde(skip_serializing_if = "Option::is_none")]
pub dvalue: Option<u64>,

/// Sets whether this range break is enabled.
#[serde(skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
}

impl Default for RangeBreak {
fn default() -> Self {
Self::new()
}
}

impl RangeBreak {
pub fn new() -> Self {
Self {
bounds: None,
pattern: None,
values: None,
dvalue: None,
enabled: None,
}
}

pub fn bounds(mut self, lower: impl Into<String>, upper: impl Into<String>) -> Self {
self.bounds = Some([lower.into(), upper.into()]);
self
}

pub fn pattern(mut self, pattern: impl Into<String>) -> Self {
self.pattern = Some(pattern.into());
self
}

pub fn values(mut self, values: Vec<impl Into<String>>) -> Self {
self.values = Some(values.into_iter().map(|v| v.into()).collect());
self
}

pub fn dvalue(mut self, dvalue: u64) -> Self {
self.dvalue = Some(dvalue);
self
}

pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = Some(enabled);
self
}
}
Loading