使用单独的数据集时position_dodge

时间:2018-04-16 19:06:18

标签: r ggplot2 graphics

我试图产生一个显示两组误差线的图,但不同的误差线代表不同的中心趋势/变异性估计值(例如,sd的均值和分位数的中值)。我试图使用position_dodge,但它不起作用,我怀疑这是因为我从不同的数据集中提取它的值。这是一个可重复的例子:

    #### simulate dosages
dose = factor(rep(c("small", "medium", "large"), times=10))
dose = relevel(dose, "small")

    #### simulate fevers, based on dosage (but highly skewed)
fever = rnorm(length(dose), 100, 1)
betas = matrix(c(0, -3, -6), nrow=1)
fever = fever + as.numeric(betas%*%t(model.matrix(fever~dose)))

    #### put into data frame
d = data.frame(dose=dose, fever=fever)

    #### compute means and standard errors
means = d %>% group_by(dose) %>% summarise(mean=mean(fever), lower=mean - sd(fever), upper = mean + sd(fever))
medians = d %>% group_by(dose) %>% summarise(median=median(fever), lower=quantile(fever, .25), upper = quantile(fever, .75))

    #### put all into a ggplot
ggplot(d, aes(x=dose, y=fever)) +
    geom_jitter(alpha=.2, width=.2) +
    geom_point(data=means, aes(x=dose, y=mean)) +
    geom_point(data=medians, aes(x=dose, y=median), col="red") +
    geom_errorbar(data=means, aes(y=mean, ymin=lower, ymax=upper), width=.2, position=position_dodge(width=.2)) + 
    geom_errorbar(data= medians, aes(y=median, ymin=lower, ymax=upper), width=.2, position=position_dodge(width=.2), col="red") 

其中给出了以下图像的结果:

enter image description here

注意躲避不起作用。

我们假设我不能只使用stat_summary(我不能......我实际上比较了来自另一个包的一些稳健估计的方法)。有没有办法抵消错误条/点,以便更好地看到它们?

1 个答案:

答案 0 :(得分:1)

合并两个统计信息的数据框,以便在group上映射统计信息的类型:

means <- df %>% 
  group_by(dose) %>% 
  summarise(Statistic = "Mean", Value = mean(fever), lower=mean(fever) - sd(fever), upper = mean(fever) + sd(fever)) 

medians <- df %>% 
  group_by(dose) %>% 
  summarise(Statistic = "Median", Value = median(fever), lower=quantile(fever, 0.25), upper = quantile(fever, 0.75)) 

df2 <- bind_rows(means, medians)

#### put all into a ggplot
ggplot(df, aes(x = dose, y = fever)) +
  geom_jitter(alpha = .2, width = .2) +
  geom_point(data = df2, aes(x = dose, y = Value, color = Statistic)) +
  geom_errorbar(data = df2, aes(y = Value, ymin = lower, ymax = upper, 
                group = Statistic, color = Statistic), 
                width=.2, position = position_dodge(width = .2))  

enter image description here