Reputation:
I use the following code to create a boxplot:
plot <- ggplot(WL, aes(y = wavelength, x = factor(category, level = c("A", "B")))) +
theme_bw() +
geom_boxplot(outlier.colour = "gray30", outlier.shape = 8, outlier.size = 2, lwd=1, fill = c("#C6DBEF", "#FEE391")) +
ylab(expression(lambda[(km)])) +
theme(plot.margin = unit(c(2,2,2,2), "cm"),
axis.title.x = element_blank(),
axis.title.y=element_text(size=20),
plot.title = element_text(size = 22, vjust = 2))
How can I add a legend? I want to place it inside the plot (topright). It should show the two colors and a description.
I am trying to use legends() which does not work for me.
Upvotes: 0
Views: 1349
Reputation: 17205
The issue is where you specified the fill
- The following code will give you a legend, and changing the position
in the last line will allow you to change it where you want:
# sample data
WL <- data.frame(wavelength = rnorm(100, 0,1),
category = sample(LETTERS[1:2], 100, replace = TRUE))
# plot
ggplot(WL, aes(y = wavelength, x = factor(category, level = c("A", "B")), fill = category)) +
theme_bw() +
geom_boxplot(outlier.colour = "gray30", outlier.shape = 8, outlier.size = 2, lwd = 1) +
ylab(expression(lambda[(km)])) +
theme(plot.margin = unit(c(2,2,2,2), "cm"),
axis.title.x = element_blank(),
axis.title.y=element_text(size=20),
plot.title = element_text(size = 22, vjust = 2)) +
scale_fill_manual(values = c("#C6DBEF", "#FEE391")) +
theme(legend.position = "bottom")
Upvotes: 0