Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tweak the extent to which an axis is drawn in ggplot2? [duplicate]

Tags:

plot

r

ggplot2

I am relatively new to ggplot2, having used base graphics in R for many years. One thing I always liked about base graphics is the extra padding in the axes, so that the two axes do not tend to touch in the origin. Here is a simple example in base graphics:

png(file="base.png")
plot(x,y, bty="n")
dev.off()

which makes:

base graphics

whereaas, when I do something similar in ggplot2

require(ggplot2)
x <- y <- 1:10
png(file="qplot.png")
qplot(x, y) + theme_classic()
dev.off()

I get:

qplot graphics

How can I adjust the extent to which axes are drawn? e.g. for the y axis, I'd prefer it to stop at 10.0, rather than continuing to about 10.5?

Update: thanks for the comments. I now have what I'd like; here's a snippet that draws the axes out only as far as the min/max tick on each axis.

o = qplot(x, y) + theme_classic() +
  theme(axis.line=element_blank())
oo = ggplot_build(o)
xrange = range(oo$panel$ranges[[1]]$x.major_source)
yrange = range(oo$panel$ranges[[1]]$y.major_source)
o = o + geom_segment(aes(x=xrange[1], xend=xrange[2], y=-Inf, yend=-Inf)) +
  geom_segment(aes(y=yrange[1], yend=yrange[2], x=-Inf, xend=-Inf))
plot(o)

better axes

like image 205
Stephen Eglen Avatar asked Aug 15 '14 13:08

Stephen Eglen


2 Answers

With argument expand= of functions scale_x_continuous() and scale_y_continuous() you can get axis that start and end at particular values. But if you don't provide those values then it will look as points are cut.

qplot(x, y) + theme_classic()+
      scale_x_continuous(expand=c(0,0))

enter image description here

To get the look as for base plot one workaround would be to remove axis lines with theme() and then add instead of them the lines just from values 2 to 10 (for example) with geom_segment().

qplot(x, y) + theme_classic()+
      scale_x_continuous(breaks=seq(2,10,2))+
      scale_y_continuous(breaks=seq(2,10,2))+
      geom_segment(aes(x=2,xend=10,y=-Inf,yend=-Inf))+
      geom_segment(aes(y=2,yend=10,x=-Inf,xend=-Inf))+
      theme(axis.line=element_blank())

enter image description here

like image 102
Didzis Elferts Avatar answered Sep 29 '22 09:09

Didzis Elferts


You can tweak this behavior by influencing the way the y-axis is scaled. ggplot2 usually chooses the limits according to the data and expands the axis a litte.

The following example sets expansion to zero and uses custom limits instead for more control over the axes. As you can see, however, having the axes end at the maximum value is not always beneficial as the point characters may get cut off. So a little extra space is advised..

require(ggplot2)
x <- y <- 1:10
qplot(x, y) + theme_classic() +
  scale_y_continuous(limits=c(-0.5,10), expand=c(0,0))
like image 40
SimonG Avatar answered Sep 29 '22 08:09

SimonG