Next time please consider include some reproducible example so it would be easier for other to support you in finding a good answer ;)
For legend to be displayed in ggplot2
you need to map the colour
or fill
inside the mapping
param with aes()
instead of what you are doing in the questions. The code below is a way to achieve what you want to do.
I also re-format the code a bit in my personal preference where the configuration of the plot scales
, labels
, theme
are all at the bottom while the geom
is at the top of ggplot
command. This is just personal preference.
Hope this help you get better understanding of the legend in ggplot2
.
color_names <- c("prediction 2020 bounds", "median 2020")
color_values <- c("blue", "red")
names(color_values) <- color_names
ggplot() +
# Points without corona
geom_line(data=prediction2020_bounds, aes(x = Date, y = lwr,
# assign the colour to the same name as blue value of color_values
colour = "prediction 2020 bounds"), linetype = "solid") +
geom_line(data=prediction2020_bounds, aes(x = Date, y = upr,
# assign the colour to the same name as blue value of color_values
colour = "prediction 2020 bounds"), linetype = "solid") +
geom_ribbon(data=prediction2020_bounds, aes(x = Date, ymin = lwr, ymax = upr),
alpha=.4) +
geom_point(data=prediction2020_bounds, aes(x=Date, y=Price,
# assign the fill to the same name as blue value of color_values
fill="prediction 2020 bounds"),
colour="darkblue", size=1) +
#Points with corona 2020 year
geom_point(data=median2020, aes(x=Date, y=Price,
# assign the colour to the same name as red value of color_values
fill="median 2020"),
colour="median 2020", size=1) +
# plot configuration scales, theme, etc...
labs(x = "Date", y = "Median Daily Price",
title = "Daily Median Price", colour = "Legend Title\n") +
scale_x_date(date_breaks="1 month", date_labels="%Y %m") +
scale_colour_manual(values = color_values) +
scale_fill_manual(values = color_values) +
theme_bw()
In addition to that you can use theme(legend.position = [position]
where
[position]
can be
none
: for no legend display
left/right/botom/top
: corresponded position relate to the main plot area
I found this article is very informative with thorough explaination
https://aosmith.rbind.io/2018/07/19/manual-legends-ggplot2/