I would like to draw plotly graphs with rangeslider (including start/end range), yet printing quarter dates on the X-axis, instead of the usual ymd format, as shown in the example below ; ie printing "Q1 2019" instead of "Jan 2019" :
library(plotly)
library(zoo)
d <- tibble::tibble(
time = as.yearqtr(seq(as.Date("2016-01-01"), as.Date("2020-08-31"), by = "quarters")),
y = rnorm(seq_along(time))
)
d$time <- as.Date(d$time, format = "%Y-%m-%d")
plot_ly(d, x = ~time, y = ~y) %>%
add_lines() %>%
rangeslider(d$time[10], d$time[19])
You can do this with layout
using ticktext
and tickvals
. This is the code that will ensure you see years and quarters on the X-axis.
plot_ly(d, x = ~time, y = ~y) %>%
add_lines() %>%
rangeslider(d$time[10], d$time[19]) %>%
layout(xaxis = list(ticktext = paste0(c(rep(2018, 3),
rep(2019, 4),
rep(2020, 2)),
" Q",
c(2:4, 1)),
tickvals = d$time[10:18]
))
Using set.seed()
makes the code repeatable, (since you used rnorm
). I used set.seed(3958)
if you wanted to see the same output.
Another way that you can customize the text is through the zoom level. Plotly references this site for the formatting here. There are a few examples on Plotly's website, as well. Check it out .
plot_ly(d, x = ~time, y = ~y) %>%
add_lines() %>%
rangeslider(d$time[10], d$time[19]) %>%
layout(xaxis = list(
tickformatstops = list(
list(dtickrange = list(NULL, "M1"),
value = "%Y %b"),
list(dtickrange = list("M1", "M6"),
value = "%Y Q%q"),
list(dtickrange = list("M6", NULL),
value = "%Y Y")
)))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.