使用因子作为 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

最佳答案

你想要 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 箱线图,除非您给出一个假的 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

关于r - 使用 geom_boxplot 的因子时更改 x 轴限制,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31016578/

10-13 04:00