Maral Dorri
Maral Dorri

Reputation: 478

How to add legend of boxplot and points in ggplot2?

I have the following to plot a boxplot of some data "Samples" and add points of the "Baseline" and "Theoretical" data.

library(reshape2)
library(ggplot2)

meltshear <- melt(Shear)
samples <- rep(c("Samples"), each = 10)
baseline <- c("Baseline",samples)
method <- rep(baseline, 4)
xlab <- rep(c("EXT.Single","EXT.Multi","INT.Single","INT.Multi"), each = 11)
plotshear <- data.frame(Source = c(method,"theoretical","theoretical","theoretical"), 
                    Shear = c(xlab,"EXT.Multi","INT.Single","INT.Multi"), 
                    LLDF = c(meltshear[,2],0.825,0.720,0.884))
data <- subset(plotshear, Source %in% c("Samples"))
baseline <- subset(plotshear, Source %in% c("Baseline"))
theoretical <- subset(plotshear, Source %in% c("theoretical"))
ggplot(data = data, aes(x = Shear, y = LLDF)) + geom_boxplot(outlier.shape = NA) +
  stat_summary(fun = mean, geom="point", shape=23, size=3) + 
  stat_boxplot(geom='errorbar', linetype=1, width=0.5) + 
  geom_jitter(data = baseline, colour = "green4") +
  geom_jitter(data = theoretical, colour = "red")

I get the following plot but I cannot add the legend to the plot. I want to have the legend showing labels = c("Samples","Baseline","Theoretical") for the boxplot shape, green dot, and red dot respectively.

plot

Upvotes: 0

Views: 534

Answers (1)

Mike V
Mike V

Reputation: 1364

You could try to add fill into aes.

 ggplot(data = data, aes(x = Shear, y = LLDF, fill = Shear))

Or you can see this resource, maybe it is useful http://www.cookbook-r.com/Graphs/

Upvotes: 2

Related Questions