1

I have a data.frame df as follows,

df <- data.frame(x = 0:50, y = rnorm(n = 51, mean = 25, sd = 74))

I want to annotate the axis ticks outside the plot in ggplot2. Following this question, I am able to do it as follows,

library(ggplot2)

ggplot(df, aes(x = x, y = y)) +
  geom_line() +
  geom_vline(xintercept = c(12, 28), colour = "red") +
  scale_x_continuous(breaks = c(0,12, 25,28,50), labels = c("0","Point 1", "25","Point 2","50")) +
  theme(axis.text.x = element_text(color = c("black","red", "black", "red", "black")),
        axis.ticks.x = element_line(color = c("black","red", "black", "red", "black"),
                                    size = c(.5,1,.5,1,.5)))

enter image description here However, when the points are close, the annotations overlap.

ggplot(df, aes(x = x, y = y)) +
  geom_line() +
  geom_vline(xintercept = c(30, 28), colour = "red") +
  scale_x_continuous(breaks = c(0, 25,28, 30, 50), labels = c("0","25","Point 1", "Point 2","50")) +
  theme(axis.text.x = element_text(color = c("black","black", "red", "red", "black")),
        axis.ticks.x = element_line(color = c("black","black", "red", "red", "black"),
                                    size = c(.5,.5,1,1,.5)))

enter image description here

How to avoid this and get a desired plot as follows in ggplot2? enter image description here

Crops
  • 5,024
  • 5
  • 38
  • 65

1 Answers1

1

What about turning them using angle so they don't overlap.

ggplot(df, aes(x = x, y = y)) +
  geom_line() +
  geom_vline(xintercept = c(30, 28), colour = "red") +
  scale_x_continuous(breaks = c(0, 25,28, 30, 50), labels = c("0","25","Point 1", "Point 2","50")) +
  theme(axis.text.x = element_text(color = c("black","black", "red", "red", "black"), angle = 60, hjust = 1),
        axis.ticks.x = element_line(color = c("black","black", "red", "red", "black"),
                                    size = c(.5,.5,1,1,.5)))
Geochem B
  • 418
  • 3
  • 13