I am trying to plot a timeseries in ggplot such that the yearly values are connected with geom_line() and the totals appear as separate geom_point() at the far right of the x-axis.
I have tried to subset the data within the aesthetic, but get the error:
Aesthetics must be either length 1 or the same as the data (1): x, y
I have also tried to use two different data frames but get a similar error. Sorry if this is a basic question, but I have had no luck finding a solution.
Please see the dummy dataset and ggplot2 script below. I would like the final plot to look like this but without the line connecting '2017' and 'total', and preferably without having to resort to editing the output in Adobe Illustrator!
Any help appreciated.
library(ggplot2)
##synthetic data
Year <- seq(1996,2017)
var1 <- sample(0:10,length(Year), replace=TRUE)
var2 <- sample(0:10,length(Year), replace=TRUE)
var3 <- sample(0:10,length(Year), replace=TRUE)
var4 <- sample(0:10,length(Year), replace=TRUE)
total <- c("total",sample(0:10,4, replace=TRUE))
dat <- data.frame(Year, var1,var2,var3,var4)
dat <- rbind(dat,total)
plt <- ggplot(data=dat, aes(x=Year))
plt <- plt +
geom_point(aes(y=var1, colour = "var1")) +
geom_point(aes(y=var2, colour = "var2")) +
geom_point(aes(y=var3, colour= "var3")) +
geom_point(aes(y=var4, colour = "var4")) +
geom_line(aes(y=var1, group=1, colour = "var1")) +
geom_line(aes(y=var2, group=1, colour="var2")) +
geom_line(aes(y=var3, group=1, colour="var3"))+
geom_line(aes(y=var4, group=1, colour= "var4")) +
scale_colour_manual("",
breaks = c("var1", "var2", "var3", "var4"),
values = c("#d7191c","#fdae61","#abd9e9","#2c7bb6"))
See Question&Answers more detail:
os