使用geom_boxplot因子时更改x轴限制

时间:2015-06-24 02:25:44

标签: r ggplot2

当使用因子作为x轴刻度时,是否可以将两侧的x轴限制增加1。例如,在下图中是否可以将xlimits更改为3和9?即xlim(3,9)

p <- ggplot(mtcars, aes(factor(cyl), mpg))
p + geom_boxplot()

尝试xlim()时,我得到了:

Error: Discrete value supplied to continuous scale

当我尝试scale_x_continuous(limits = c(3,9))时,我得到了:

Error in if (zero_range(from) || zero_range(to)) return(rep(mean(to),  : 
  missing value where TRUE/FALSE needed
In addition: Warning messages:
1: In loop_apply(n, do.ply) :
  no non-missing arguments to min; returning Inf
2: In loop_apply(n, do.ply) :
  no non-missing arguments to max; returning -Inf
3: In loop_apply(n, do.ply) :
  position_dodge requires constant width: output may be incorrect

1 个答案:

答案 0 :(得分:3)

你想要scale_x_discrete

p <- ggplot(mtcars, aes(factor(cyl), mpg))
p + geom_boxplot() + scale_x_discrete(limits = c("4","6"))

xlim

p <- ggplot(mtcars, aes(factor(cyl), mpg))
p + geom_boxplot() + xlim("4", "6")

编辑:要求包括更广泛的范围。要包含其他值,您需要在一系列因子上使用break函数:

p <- ggplot(mtcars, aes(factor(cyl), mpg))
p + geom_boxplot() +
    scale_x_discrete(breaks = factor(3:9), limits = c("3", "4", "5", "6", "7", "8", "9"))

在这种情况下,你必须绘制出8 cyl boxplot,除非你假装8:

p + geom_boxplot() +
  scale_x_discrete(breaks=factor(c("3","4","5","6","7", "eight", "9")),
                   limits = c("3", "4", "5", "6", "7", "eight", "9") 

或在绘图之前将其过滤掉:

mtcars<-mtcars[mtcars$cyl!=8,]

参考:scale_x_discrete