2017-02-25 64 views
6

我有一個ggplot圖。我需要將誤差線相對於抖動點。我的代碼是:如何移動兩個geoms相對於彼此的x軸位置

data("cabbages", package = "MASS") 

require("ggplot2") 

pos_1 <- position_jitterdodge(
    jitter.width = 0.25, 
    jitter.height = 0, 
    dodge.width = 0.9 
) 

gg <- 
    ggplot(data = cabbages, 
      aes(
       x  = Cult, 
       y  = HeadWt, 
       colour = Cult, 
       fill = Cult 
       )) + 

    geom_jitter(alpha = 0.4, position = pos_1) + 

    stat_summary(fun.y = "mean", geom = "point", size = 3) + 

    stat_summary(fun.data = "mean_cl_normal", 
       geom = "errorbar", 
       width = 0.05, 
       lwd = 1, 
       fun.args = list(conf.int = 0.95) 
) + 

    theme_bw() 

print(gg) 

目前的結果是:

enter image description here

我需要這樣的:

enter image description here

回答

5

您可以在aes在加一個偏移量x每個stat_summaryaes(x = as.numeric(Cult) + 0.2)):

ggplot(data = cabbages, 
     aes(x = Cult, 
      y  = HeadWt, 
      colour = Cult, 
      fill = Cult)) + 
    geom_jitter(alpha = 0.4, position = pos_1) + 
    stat_summary(aes(x = as.numeric(Cult) + 0.2), fun.y = "mean", geom = "point", size = 3) + 
    stat_summary(aes(x = as.numeric(Cult) + 0.2), fun.data = "mean_cl_normal", 
       geom = "errorbar", 
       width = 0.05, 
       lwd = 1, 
       fun.args = list(conf.int = 0.95)) + 
    theme_bw() 

enter image description here

+0

注意,在構建的情節,你需要一個明確的x軸的'geom' _before_你添加一個'geom'用'X = as.numeric(因素)0.1 '。你添加的第一個'geom'設置了x軸的類型,所以如果你先用'x = as.numeric(factor)+ 0.1'添加'geom',那麼x軸將是連續的,你可以' t將一個因子變量添加到連續軸(除非您首先使用'as.numeric()'將其轉換)。 – filups21