Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R ggplot2: Setting additional specific axis tick marks

Tags:

r

ggplot2

I have a ggplot:

ggplot()+geom_line(data = data.frame(y = c(1,2,3), x=c(1,2,3)), aes(y=y,x=x))

enter image description here I want to keep the default axis breaks and labels (In my program, I do not know the limits of the plot a priori.)

At x= 1.5 I want to add an additional tick mark to the x-axis with label "hi".

I know about scale_x_continuous(), but I do not know how to access the "default breaks computed by the transformation object".

like image 380
PascalIv Avatar asked Mar 23 '26 13:03

PascalIv


1 Answers

ggplot2 uses the base function pretty (indirectly through scales::pretty_breaks) for non-transformed axes. Use this to your advantage:

df <- data.frame(y = c(1,2,3), x=c(1,2,3))

ggplot(df, aes(x, y)) + 
  geom_line() +
  scale_x_continuous(breaks = c(pretty(df$x), 1.5), labels = c(pretty(df$x), 'hi'))

At 1.5 it will overplot of course (you write 'additional', not 'replace', so I'm not sure what you're after). If you don't want that, you'll need to do something like:

pretty_br <- pretty(df$x)[abs(pretty(df$x) - 1.5) > 0.25]
ggplot(df, aes(x, y)) + 
  geom_line() +
  scale_x_continuous(breaks = c(pretty_br, 1.5), labels = c(pretty_br, 'hi'))

enter image description here

like image 133
Axeman Avatar answered Mar 26 '26 12:03

Axeman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!