I have two time series data that I want to show on the same graph. Both series have three columns: Date, County and Value. Here is my code:
#Data
Series1 <- data.frame(Date = c(2000,2001,2000,2001), County = c("a", "a", "b", "b"),Total = c(100,150,190,130))
Series2 <- data.frame(Date = c(2000,2001,2000,2001), County = c("a", "a", "b", "b"),Total = c(180,120,140,120))
#Plot data
ggplot() +
geom_line(data = Series1, aes(x = Date, y = Total, color = County), linetype="solid") +
geom_line(data = Series2, aes(x = Date, y = Total, color = County), linetype="dashed")
The plot looks like this:
Now I just need to add one legend showing that solid line represents Series1 and dashed line represents Series2. How can I do this?
Legends are created automatically when you use aes()
to map a data column to an aesthetic. You don't have a data column that you're mapping to the linetype aesthetic, so we need to create one.
Series1$series = 1
Series2$series = 2
all_series = rbind(Series1, Series2)
Now we've all the data together and plotting is easy:
ggplot(all_series,
aes(x = Date, y = Total, color = County, linetype = factor(series))) +
geom_line()
Automatic legend, only one geom_line
call, using ggplot
as it's meant to be used: with tidy data.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.