Search code examples
raxesggplot2

Character values on a continuous axis in R ggplot2


Is there a way to include character values on the axes when plotting continuous data with ggplot2? I have censored data such as:

   x  y Freq
1 -3 16    3
2 -2 12    4
3  0 10    6
4  2  7    7
5  2  4    3

The last row of data are right censored. I am plotting this with the code below to produce the following plot:

a1 = data.frame(x=c(-3,-2,0,2,2), y=c(16,12,10,7,4), Freq=c(3,4,6,7,3))
fit = ggplot(a1, aes(x,y)) + geom_text(aes(label=Freq), size=5)+
  theme_bw() +
  scale_x_continuous(breaks = seq(min(a1$x)-1,max(a1$x)+1,by=1),
                     labels = seq(min(a1$x)-1,max(a1$x)+1,by=1),
                     limits = c(min(a1$x)-1,max(a1$x)+1))+
  scale_y_continuous(breaks = seq(min(a1$y),max(a1$y),by=2))

enter image description here

The 3 points at (2,4) are right censored. I would like them to be plotted one unit to the right with the corresponding xaxis tick mark '>=2' instead of 3. Any ideas if this is possible?


Solution

  • It is quite possible. I hacked the data so 2,4 it's 3,4. Then I modified your labels which can be whatever you want as long as they are the same length as the breaks.

    ggplot(a1, aes(x,y)) + geom_text(aes(label=Freq), size=5)+
    theme_bw() +
    scale_x_continuous(breaks = seq(min(a1$x)-1,max(a1$x),by=1),
                       labels = c(seq(min(a1$x)-1,max(a1$x)-1,by=1), ">=2"),
                       limits = c(min(a1$x)-1,max(a1$x)))+
    scale_y_continuous(breaks = seq(min(a1$y),max(a1$y),by=2))
    

    enter image description here