I need to draw line segments across (and on) the x-axis boundary of a ggplot2
figure so that I can make axis breaks. This SO question is similar but does not have an answer for how to implement multiple axis breaks and the top answer is rather cumbersome.
Example Data
set.seed(321)
dat <- data.frame(matrix(ncol = 2, nrow = 18))
colnames(dat)[1:2] <- c("Month", "Value")
dat$Month <- rep(c(1,2,10,11,20,21),3)
dat$Value <- rnorm(18,20,2)
This is the basic figure, note the theme is theme_bw()
. I would like to keep this theme so that this figure resembles others. In the similar SO question, the top answer does not use theme_bw()
.
library(ggplot2)
ggplot(data = dat, aes(x = factor(Month), y = Value)) +
geom_boxplot() +
labs(x = "Month") +
scale_y_continuous(breaks = seq(15,24,1),
limits = c(15,24)) +
theme_bw() +
theme(panel.grid = element_blank(),
text = element_text(size = 16),
axis.text.x = element_text(size = 14, color = "black"),
axis.text.y = element_text(size = 14, color = "black"))
This is as far as I got because I could not find a way to extend the geom_segment()
across the x-axis boundary.
ggplot(data = dat, aes(x = factor(Month), y = Value)) +
geom_boxplot() +
labs(x = "Month") +
geom_segment(aes(x = 2.45, xend = 2.45,
y = -Inf, yend = 15)) +
geom_segment(aes(x = 2.55, xend = 2.55,
y = -Inf, yend = 15)) +
geom_segment(aes(x = 4.45, xend = 4.45,
y = -Inf, yend = 15)) +
geom_segment(aes(x = 4.55, xend = 4.55,
y = -Inf, yend = 15)) +
scale_y_continuous(breaks = seq(15,24,1),
limits = c(15,24)) +
theme_bw() +
theme(panel.grid = element_blank(),
text = element_text(size = 16),
axis.text.x = element_text(size = 14, color = "black"),
axis.text.y = element_text(size = 14, color = "black"))
The ideal figure would look like the figure below, which I created 'by-hand' in MS Word which I am trying to avoid.
It would be great if ggbreak
had a way to do this but it currently does not as far as I am aware.