Reputation: 59
Is there an easy way to move the ticks of an axis with discrete values so that they are on the plot limits and midway between two labels?
My code:
p2 <- ggplot(diamonds, aes(cut, price)) +
geom_boxplot() +
theme_bw() +
theme(panel.grid = element_blank())
p2 +
geom_vline(xintercept = c(1.5, 2.5, 3.5, 4.5),
colour = "gray92") +
scale_x_discrete(expand = c(0,0.5))
What I would like (notice ticks on x axis):
Upvotes: 0
Views: 284
Reputation: 123783
One option or hack would be to use a continuous x scale which allows to set the breaks and ticks midway between two labels and add the "axis labels" via a geom_text
or a geom_label
as I do in my code below. To this end convert variable to be mapped on x to a numeric.
library(ggplot2)
ggplot(diamonds, aes(as.numeric(factor(cut)), price, group = cut)) +
geom_boxplot() +
theme_bw() +
theme(panel.grid = element_blank()) +
geom_vline(xintercept = c(1.5, 2.5, 3.5, 4.5),
colour = "gray92") +
scale_x_continuous(breaks = 0:5 + .5, labels = ~ rep("", length(.x)), expand = c(0, .125)) +
geom_label(aes(label = cut, y = -Inf), data = ~ dplyr::distinct(.x, cut),
fill = NA, vjust = 1,
label.size = 0,
label.padding = unit(5, "pt")) +
coord_cartesian(clip = "off")
Upvotes: 1