Change the number of breaks using facet_grid in ggplot2

后端 未结 1 960
青春惊慌失措
青春惊慌失措 2020-12-06 03:39

I have a kind of data such as:

y<-rep(c(1, 2, 3), times=5)
group<-rep(c(\"a\", \"b\", \"c\", \"d\", \"e\"), each=3)
x<-c(2, 3, 4, 5, 7, 10, 10, 15,          


        
相关标签:
1条回答
  • 2020-12-06 03:59

    You can define your own favorite breaks function. In the example below, I show equally spaced breaks. Note that the x in the function has a range that is already expanded by the expand argument to scale_x_continuous. In this case, I scaled it back (for the multiplicative expand argument).

    # loading required packages
    require(ggplot2)
    require(grid)
    # defining the breaks function, 
    # s is the scaling factor (cf. multiplicative expand)
    equal_breaks <- function(n = 3, s = 0.05, ...){
      function(x){
        # rescaling
        d <- s * diff(range(x)) / (1+2*s)
        seq(min(x)+d, max(x)-d, length=n)
      }
    }
    # plotting command 
    p <- ggplot(a, aes(x, y)) + 
      geom_point() + 
      facet_grid(~group, scales="free_x") +
      # use 3 breaks, 
      # use same s as first expand argument, 
      # second expand argument should be 0
      scale_x_continuous(breaks=equal_breaks(n=3, s=0.05), 
                         expand = c(0.05, 0)) + 
      # set the panel margin such that the 
      # axis text does not overlap 
      theme(axis.text.x = element_text(angle=45), 
            panel.margin = unit(1, 'lines'))
    

    resulting image

    0 讨论(0)
提交回复
热议问题