How can I adjust the degree to which the axis is plotted in ggplot2?

I am relatively new to ggplot2, have been using basic graphics in R for years now. One thing I've always liked basic graphics is the additional padding in the axes so that the two axes don't tend to touch the origin. Here's a simple example in basic graphics:

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

      

which does:

base graphics

where when i do something like this 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 degree to which the axes are drawn? for example for the y-axis, would I prefer it to stop at 10.0 rather than continue until about 10.5?

Update: thanks for the comments. Now I have what I would like; here's a snippet that only draws the axes up to the min / max mark 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

+3


source to share


2 answers


With the expand=

function argument scale_x_continuous()

and, scale_y_continuous()

you can get an axis that starts and ends with specific values. But if you don't provide these values, then it looks like the dots will be truncated.

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

      

enter image description here



To get an idea of ​​the underlying plot, one way would be to remove the axes with theme()

, and then instead add rows with only values ​​from 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

+5


source


You can customize this behavior by affecting how the y-axis is scaled. ggplot2

usually selects the limits according to the data and extends the axis a litte.

The following example sets the extension to zero and instead uses custom constraints for more control over the axes. However, as you can see, the ones ending in the maximum value are not always beneficial, since the characters of the points can be clipped. Therefore, a little extra space is recommended.



require(ggplot2)
x <- y <- 1:10
qplot(x, y) + theme_classic() +
  scale_y_continuous(limits=c(-0.5,10), expand=c(0,0))

      

+1


source







All Articles