I am trying to figure out how to add a manual legend to a ggplot2 figure. From my reading, you have to add color to aes. However, from all of the examples that I have seen, the color is used for a factor variable. I have a line plot with three continuous variables. I need to add a simple legend for the colors.
I think you will get the legend you want if you use gather (or pivot_longer) to bring all the rates into one column and then use group and colour mappings in the aesthetic.
library(tidyr)
df <- gather(by_year_percentage, key = measure, value = Rate,
c("deathpercentage", "tamponadepercentage", "protaminepercentage"))
ggplot(df, aes(x=arrivaldate, y = Rate, group = measure, colour = measure)) +
geom_line()
The previous solution is the best way but if you want to use wide dataframes you can do it with. I would suggest the long format as it makes life a lot easier. You need to map the color to a name in the aes(_) statement and then define the color, fill or shape.
I just want to point out that you can keep your underlying data in whatever shape is most convenient and just reshape it temporarily for plotting with ggplot. For example, you can reshape on the fly using the pipe (%>%) operator:
library(tidyverse)
gather(by_year_percentage, key = measure, value = Rate,
deathpercentage, tamponadepercentage, protaminepercentage) %>%
ggplot(aes(x=arrivaldate, y = Rate, group = measure, colour = measure)) +
geom_line()
If you're going to be using ggplot regularly, it will work much more effectively if you put your data in "long" format for plotting, regardless of what shape you keep your data in for other purposes.