13

Using ggplot, is it possible to get "R-style" x/y axes that don't meet at the origin and that instead consist of two disconnected ranges, as in the following example?

enter image description here

The reason here is mainly to get ggplot plots to look consistent next to pure-R ones.

joran
  • 169,992
  • 32
  • 429
  • 468
Christian
  • 1,499
  • 2
  • 12
  • 28
  • 3
    this begs the question, why not make base plots [look like ggplot2?](http://rwiki.sciviews.org/doku.php?id=tips:graphics-misc:ggplot2theme_inbase) ;) – baptiste May 30 '12 at 01:19
  • Because I can neither update nor redo the base plots. I've actually considered editing the SVG of the ggplot-generated ones, but that's such a hack. – Christian May 30 '12 at 01:22
  • If you want to digitize the base plots, you could try the package `digitize`. – mnel May 30 '12 at 02:53

1 Answers1

15

Try this,

library(ggplot2)

d <- data.frame(x=1:10, y=rnorm(10))

base_breaks_x <- function(x){
  b <- pretty(x)
  d <- data.frame(y=-Inf, yend=-Inf, x=min(b), xend=max(b))
  list(geom_segment(data=d, aes(x=x, y=y, xend=xend, yend=yend), inherit.aes=FALSE),
       scale_x_continuous(breaks=b))
}
base_breaks_y <- function(x){
  b <- pretty(x)
  d <- data.frame(x=-Inf, xend=-Inf, y=min(b), yend=max(b))
  list(geom_segment(data=d, aes(x=x, y=y, xend=xend, yend=yend), inherit.aes=FALSE),
       scale_y_continuous(breaks=b))
}

ggplot(d, aes(x,y)) +
  geom_point() +
  theme_bw() +
  theme(panel.border = element_blank(),
       panel.grid.major = element_blank(),
       panel.grid.minor = element_blank()) +
  base_breaks_x(d$x) +
  base_breaks_y(d$y)

screenshot

Edit: a related issue has since been discussed in the ggtheme package, and potentially provides a cleaner solution (no need to provide the data explicitly to the breaks function).

baptiste
  • 75,767
  • 19
  • 198
  • 294