2015-06-24 74 views
2

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

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 

回答

2

你想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") 

编辑:要求包括更宽的范围。要包括其他值,则需要使用中断功能,各种因素的列表:

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缸箱线图,如果你不给假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

+0

是否有可能使得极限低于4(3)并且高于8(9)而不会出现错误?这样做的理由是将其与条形图进行对照。 – Getch