Expand Categorical x-axis in ggplot

前端 未结 2 834
遥遥无期
遥遥无期 2021-01-19 18:48

I can\'t figure out how to use expand() within scale_x_discrete() to expand a categorical x-axis so that placing a label to the right of points won

相关标签:
2条回答
  • 2021-01-19 19:12

    Since I'm facing the same problem... I found expand_limits(...) quite useful here:

    dat <- data.frame(x= c('a', 'b', 'c'), y= 1:3)
    ggplot(data= dat, aes(x= x, y= y)) + 
        geom_point() + 
        expand_limits(x= c(-1, 5))
    

    Or, to avoid hardcoding the limits:

        expand_limits(x= c(-1, length(levels(dat$x)) + 2))
    

    (With ggplot2_3.1.0)

    0 讨论(0)
  • 2021-01-19 19:24

    You could just append a blank level to the existing levels of your categorical variable, as in:

    data(iris)
    
    levels(iris$Species) <- c(levels(iris$Species),'') # add blank level
    
    library(ggplot2)
    ggplot(data = iris, aes(x = Species, y = Sepal.Width)) +
      geom_jitter() +
      scale_x_discrete(drop=FALSE) # don't drop unused blank level
    

    Update: Or, if you really want to extend the x axis by a numeric value then you could first convert the categorical to numeric via as.integer():

    data(iris)
    specVals <- levels(iris$Species)
    iris$Species <- as.integer(iris$Species)
    
    library(ggplot2)
    ggplot(data = iris, aes(x = Species, y = Sepal.Width)) +
      geom_jitter(height=0) + # on 2nd thought -- don't add noise to the quantitative axis
      scale_x_continuous(limits=c(min(iris$Species)-0.5,max(iris$Species)+1),
                         breaks=(min(iris$Species)):(max(iris$Species)+1), 
                         labels=c(specVals,''))
    

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