2014-10-09 78 views
0
library(ggplot2) 
library(Hmisc) 
data(mtcars) 
myplot <- ggplot(mtcars, aes(x = as.factor(cyl), y = qsec)) + 
    geom_boxplot() + 
    stat_summary(fun.y = mean, geom = "point", shape = 5, size = 2) + 
    stat_summary(fun.data = mean_cl_normal, geom = "errorbar", 
      width = 0.2) 

產生 plot躲避箱圖和誤差線與GGPLOT2

我想躲閃的均值和誤差條有點權,使得誤差線不掩蓋IQR線的boxplot。指定position=position_dodge(.5)似乎不起作用,因爲geom_errorbar不知道geom_boxplot

回答

1

您可以介紹您作爲X你errorbars偏移使用一個新的變量:

library(ggplot2) 
library(Hmisc) 
data(mtcars) 
mtcars$cyl.n <- as.numeric(as.factor(mtcars$cyl)) + .5 

(myplot <- ggplot(mtcars, aes(x = as.factor(cyl), y = qsec)) + 
    geom_boxplot() + 
    stat_summary(aes(x = cyl.n), fun.y = mean, geom = "point", shape = 5, size = 2) + 
    stat_summary(aes(x = cyl.n), fun.data = mean_cl_normal, geom = "errorbar", 
      width = 0.2)) 

enter image description here

as.numeric(as.factor(.))可確保新的錯誤欄顯示在相同的位置的間隔箱形圖,但移動了0.5個單位。

+0

這是一個整潔的想法,並解決了我的問題。謝謝! – coanil 2014-10-09 14:54:28