2015-06-24 99 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