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

前端 未结 2 1920
温柔的废话
温柔的废话 2021-01-03 02:16

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 tw

相关标签:
2条回答
  • 2021-01-03 02:30

    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

    0 讨论(0)
  • 2021-01-03 02:34

    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))
    
    0 讨论(0)
提交回复
热议问题