Reputation: 198
I'm trying to set custom ticks for specific dates on the x axis. So far I've tried:
tick0
and dtick
for regular custom ticks, though I need irregular onesThe closer I got to what I want was using the code shown below. However, the first tick I need won't show (the dates I want to use as breaks/ticks can be found in rangebreaks):
df <- tibble(
name = c("pat", "bill", "chuck", "dick", "ted"),
uni = factor(c("DM", "DM", "DM", "VM", "VM")),
cond =factor(c( "D", "E", "D", "E", "D")),
f_des = as.Date(c( "2021-07-28", "2021-11-05", "2022-02-02", "2021-07-30", "2022-03-10")),
f_ces = as.Date(c( "2021-11-04", "2022-01-15", "2022-04-10", "2022-03-10", "2022-04-10"))
)
#plot
ggplot(df, aes(fill = cond, text = name)) +
geom_rect(aes( xmin = f_des, xmax = f_ces,
ymin = as.numeric(uni) - .6 / 2, ymax = as.numeric(uni) + width / 2)) +
scale_y_continuous(breaks = seq(levels(df$uni)), labels = levels(df$uni), expand = c(0.01,0))
ggplotly(tooltip = c("text")) %>%
layout(xaxis = list(
rangebreaks = list(values= c( "2021-07-30","2021-10-07","2021-11-05","2022-02-02")),
tickcolor="crimson", gridcolor="crimson"))
Here's the ouptut: plot screenshot with less ticks/grids than expected
Upvotes: 1
Views: 1283
Reputation: 123783
There are probably more straightforward options but one option would be to first define your desired date breaks and convert them to proper Date
objects.
For the tickvals
convert the breaks to numerics, for the ticktext
format the breaks in your desired format:
library(plotly)
width <- .9
breaks <- as.Date(c("2021-07-30", "2021-10-07", "2021-11-05", "2022-02-02"))
ticktext <- format(breaks, "%b %d")
tickvals <- as.numeric(breaks)
p <- ggplot(df, aes(fill = cond, text = name)) +
geom_rect(aes(
xmin = f_des, xmax = f_ces,
ymin = as.numeric(uni) - .6 / 2, ymax = as.numeric(uni) + width / 2
)) +
scale_y_continuous(breaks = seq(levels(df$uni)), labels = levels(df$uni), expand = c(0.01, 0))
ggplotly(tooltip = c("text")) %>%
layout(xaxis = list(
ticktext = ticktext,
tickvals = tickvals,
tickcolor = "crimson",
gridcolor = "crimson"
))
Upvotes: 3