Brad
Brad

Reputation: 680

Custom legend for geom_boxplot with connective mean line

I have combined ggplot boxplots with a connecting line which is the mean average.

How could I create a legend so people know the blue circle points represent the mean average for each boxplot?

library(ggplot2)
library(scales)
options(scipen=11)

ggplot(Price, aes(x=Price$stage_code, y=Price$Realvalue)) + 
  scale_y_continuous(labels = comma) +
  geom_boxplot(notch=FALSE, outlier.shape=NA, fill="red", alpha=0.2) +
  coord_cartesian(ylim=c(0,1000000000)) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) + 
  ggtitle("Average True Value of Listed Mining Companies\nThroughout Mine Development Stages") +
  xlab("Project Development Stages") + 
  ylab("Number of Diluted Stocks x Closing Stock Price") +
  stat_summary(fun.y=mean, geom="line", linetype="dotted", 
               size=1.4, color = "Blue",alpha=0.6, aes(group=1)) +
  stat_summary(fun.y=mean, geom="point", alpha=1, color="darkblue", 
               size=3.2, shape = 21, fill = "lightblue", stroke = 2)

Boxplot + Mean line

Upvotes: 0

Views: 866

Answers (1)

Yuri Sugano
Yuri Sugano

Reputation: 26

ggplot2 only adds legends for colors assigned based on variables.

edit: I realized from this answer that the legend can be added manually. This is a much better approach.

Just map the color within aes, and use scale_color_manual to add a title and specify the colors:

stat_summary(aes(color="Legend"),fun.y=mean, geom="point", alpha=1,
             size=3.2, shape = 21, fill = "lightblue", stroke = 2) +
scale_colour_manual("Legend title", values="darkblue")

Upvotes: 1

Related Questions