Home > other >  Adding legend for geom_line to ggplot
Adding legend for geom_line to ggplot

Time:06-27

I'm generating a chart line graph with ggplot, the main purpose of the graph it to display some sample values over time for some points(the number of points can vary, there is one line for each point). There is also a line I added to show if the values exceed a predefined limit. I get a legend on the right that map each point, but I didn't manage to add a legend for the limit. Here is the code that generate the graph :

library(ggplot2)
df2 <- subset(dataset, ResultNumericValue < 1000000)
names(df2)[4] <- "PointName"
df2[[1]] <- as.POSIXct(df2[[1]], tz="GMT", format="%Y-%m-%dT%H:%M")
ggplot(df2, aes(x=SampleDate, y=ResultNumericValue))  
  geom_line(aes(color=PointName))  
  geom_point(aes(color=PointName)) 
  geom_line(aes(y = UpperLimit, color=UpperLimit), color="red", size=1)  
  labs(x = "Sample Date", y = "Sample Value", color="Points")  
  theme(panel.grid.major = element_line(color = "darkgrey", size = 0.5, linetype = 3),
  panel.background = element_rect(fill = "white", colour = "grey50"))

The looks like this :

                SampleDate           ResultNumericValue  UpperLimit    point name
1 2020-03-03T16:00:00.0000000                  4         13            1
2 2020-03-05T16:00:00.0000000                  1         13            1
3 2020-03-23T07:30:48.2870000                  2         13            1
4 2020-03-24T00:07:43.6030000                  1         13            CW1
5 2020-03-24T06:56:41.1170000                  2         13            CW1

And this is what the graph look like : enter image description here

  • Related