| 1 |
generate_random_walk <- function(num_steps = 90) { |
| 2 |
start_date <- as.POSIXct( |
| 3 |
as.integer(Sys.time()) * runif(1), |
| 4 |
origin = "1970-01-01" |
| 5 |
) |
| 6 |
|
| 7 |
increments <- rnorm(num_steps) |
| 8 |
cumulative_sum <- cumsum(increments) |
| 9 |
time_series <- c(0, cumulative_sum) + rnorm(1, 0, 50) + 25 |
| 10 |
|
| 11 |
dates <- seq(start_date, length.out = num_steps + 1, by = "day") |
| 12 |
|
| 13 |
data.frame(date = dates, value = time_series) |
| 14 |
} |
| 15 |
|
| 16 |
as_plotly_sparkline <- function(plot, color = "white") { |
| 17 |
plot |> |
| 18 |
layout( |
| 19 |
xaxis = list(visible = FALSE, showgrid = FALSE, title = ""), |
| 20 |
yaxis = list(visible = FALSE, showgrid = FALSE, title = ""), |
| 21 |
hovermode = "x", |
| 22 |
margin = list(t = 0, r = 0, l = 0, b = 0), |
| 23 |
font = list(color = color), |
| 24 |
paper_bgcolor = "transparent", |
| 25 |
plot_bgcolor = "transparent" |
| 26 |
) |> |
| 27 |
config(displayModeBar = FALSE) |> |
| 28 |
htmlwidgets::onRender( |
| 29 |
"function(el) { |
| 30 |
var ro = new ResizeObserver(function() { |
| 31 |
var visible = el.offsetHeight > 200; |
| 32 |
Plotly.relayout(el, {'xaxis.visible': visible}); |
| 33 |
}); |
| 34 |
ro.observe(el); |
| 35 |
}" |
| 36 |
) |
| 37 |
} |
| 38 |
|
| 39 |
random_plotly_plot <- function(type = NULL, color = "white") { |
| 40 |
if (is.null(type)) { |
| 41 |
type <- sample(c("bar", "box", "line"), 1) |
| 42 |
} |
| 43 |
|
| 44 |
plot <- switch( |
| 45 |
type, |
| 46 |
bar = random_plotly_bar(color, 50), |
| 47 |
box = random_plotly_box(color, 50), |
| 48 |
line = random_plotly_line(color, 50), |
| 49 |
stop("Not a valid random plot type: ", type) |
| 50 |
) |
| 51 |
|
| 52 |
as_plotly_sparkline(plot, color) |
| 53 |
} |
| 54 |
|
| 55 |
random_plotly_bar <- function(color, n = 50) { |
| 56 |
plot_ly( |
| 57 |
x = ~ runif(n), |
| 58 |
type = "histogram", |
| 59 |
histnorm = "probability", |
| 60 |
nbinsx = 10, |
| 61 |
color = I(color), |
| 62 |
stroke = I(color), |
| 63 |
alpha_stroke = 1, |
| 64 |
alpha = 0.6 |
| 65 |
) |
| 66 |
} |
| 67 |
|
| 68 |
random_plotly_box <- function(color, n = 50) { |
| 69 |
plot_ly(x = ~ rnorm(n), type = "box", color = I(color)) |
| 70 |
} |
| 71 |
|
| 72 |
random_plotly_line <- function(color, n) { |
| 73 |
add_lines( |
| 74 |
plot_ly(generate_random_walk(n)), |
| 75 |
x = ~date, |
| 76 |
y = ~value, |
| 77 |
color = I(color), |
| 78 |
fill = "tozeroy", |
| 79 |
span = I(1), |
| 80 |
alpha = 0.2 |
| 81 |
) |
| 82 |
} |