Add legend to indicate shapes

Need help adding a legend to the shapes used on the chart, as described below. The plot is as shown below: its field diagram, points for average values, error bars for the confidence interval.

The resulting graph is as follows: how to add a legend to this to communicate what they red circlesindicate meanand green error barsindicate confidence interval? - as in the image below

Legend Required

Legend

land Window graph with mean and ci

The data and code used to generate the above is provided below for reference.

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

What needs to be added to the above code to get a legend that shows a summary of statistics that circle shapes and error bars indicate?

+4
1

, . 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))))

:

, , , , , 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
    )

:

+3

Source: https://habr.com/ru/post/1659370/


All Articles