首页 文章

添加图例以指示形状

提问于
浏览
4

如下所述,需要一些帮助,为图中使用的形状添加图例 . 该图如下 - 它是一个箱形图,平均值,置信区间的误差线 .

结果图如下 - how do I add a legend to this so as to tell that the red circles indicate the mean and the green error bars indicate confidence interval ? - 如下图所示

Required legend

Legend

Plot
Box plot with mean & ci

用于生成上述内容的数据和代码在下面给出以供参考 .

df <- data.frame(cbind(mtcars[,1], mtcars[,2])) #mtcars[, 1:2]
colnames(df) <- c("metric", "group")
df$group <- factor(df$group)

p1 <- ggplot(data=df, aes(x=group, y=metric ) ) +
  geom_boxplot()

metric_means <- aggregate(df$metric, list(df$group), mean) 
metric_ci_95 <- aggregate(df$metric, list(df$group), function(x){1.96*sd(x)/sqrt(length(x))})
metric_mean_ci = data.frame(group=metric_means[,1],mean=metric_means[,2], ci=metric_ci_95[,2])

# plot mean
p1 <- p1 + geom_point(data=metric_means, aes(x=metric_means[,1], y=metric_means[,2]),
                      colour="red", shape=21, size=2)

#plot confidence interval
p1 <- p1 + geom_errorbar(data=metric_mean_ci, aes(ymin=mean-ci, ymax=mean+ci, x=group, y=mean),
                         color="green", width=.1)

p1

需要在上面的代码中添加什么才能获得显示圆和误差条形状指示的统计摘要的图例?

1 回答

  • 3

    如果您真的想单独为它们着色,可以使用此代码 . 我使用 geom_linerange 而不是 geom_errorbar 来获取图例中的垂直线 . 另外,正如所建议的那样,我在 aes 内部映射颜色以获取图例,然后我使用 override.aes 来限制每个值的绘图 .

    ggplot(data=df, aes(x=group, y=metric ) ) +
      geom_boxplot() +
      geom_point(data=metric_means
                 , aes(x=metric_means[,1]
                       , y=metric_means[,2]
                       , colour = "Mean")
                 , shape=21, size=2) +
      geom_linerange(data=metric_mean_ci
                     , aes(ymin=mean-ci
                          , ymax=mean+ci
                          , x=group
                          , y=mean
                          , color="95% CI")
                    ) +
      scale_color_manual(name = "", values = c("green", "red")) +
      guides(colour = guide_legend(override.aes = list(linetype = c("solid", "blank")
                                                       , shape = c(NA, 1))))
    

    得到:

    enter image description here

    另一种需要不太复杂的设置的方法是使用一些已经可用的功能,特别是 stat_summary

    ggplot(data=df
           , aes(x=group, y=metric ) ) +
      geom_boxplot() +
      stat_summary(
        aes(color = "Mean and 95% CI")
        , fun.data = mean_cl_normal
        )
    

    得到:

    enter image description here

相关问题