2017-02-25 58 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