如下所述,需要一些帮助,为图中使用的形状添加图例 . 该图如下 - 它是一个箱形图,平均值,置信区间的误差线 .
结果图如下 - 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
Plot
用于生成上述内容的数据和代码在下面给出以供参考 .
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 回答
如果您真的想单独为它们着色,可以使用此代码 . 我使用
geom_linerange
而不是geom_errorbar
来获取图例中的垂直线 . 另外,正如所建议的那样,我在aes
内部映射颜色以获取图例,然后我使用override.aes
来限制每个值的绘图 .得到:
另一种需要不太复杂的设置的方法是使用一些已经可用的功能,特别是
stat_summary
:得到: