Home > Enterprise >  How can I plot time series line plot of two variables in ggplot?
How can I plot time series line plot of two variables in ggplot?

Time:11-26

I want to make a line plot of date versus Ydet and Yobs in ggplot, I have tried, but couldn't achieved it. Can anyone help, please?

> library(ggplot2)

> #cbind Ydet and Yobs
> Ydet.obs <- cbind(Ydet, Yobs)

> #create ts object starting from 2001
> ts <- seq(as.POSIXct("2001-01-01"), length.out=nrow(Ydet.obs), by = "year") 
> Ydet.obs <- xts(Ydet.obs[], ts) 

> #extract date column

> Ydet.obs <- data.frame('Date' = index(Ydet.obs),  
                         coredata(Ydet.obs))
> head(Ydet.obs)
        Date Ydet Yobs
1 2001-01-01 5314 5215
2 2002-01-01 5683 5585
3 2003-01-01 5783 5690
4 2004-01-01 5816 5730
5 2005-01-01 6168 6084
6 2006-01-01 6057 5982

CodePudding user response:

There are several ways, but here is one simple:

colors <- c("Ydet" = "blue", "Yobs" = "red")

ggplot(Ydet.obs, aes(x= Date))   
  geom_line(aes(y =Ydet, color = "Ydet"))  
  geom_line(aes(y = Yobs, color = "Yobs"))   
  labs(x = "Year",
       y = "Value",
       color = "Legend")  
  scale_color_manual(values = colors)

CodePudding user response:

ggplot is really design to work with 'tidy' or long data frames, so convert your data first.

(see https://r4ds.had.co.nz/tidy-data.html)

I have made up highly simplified data as yours was not reproducible. Please see this post about making reproducibly data for asking questions in future: How to make a great R reproducible example

library(tidyr)
library(ggplot2)
Ydet.obs <- data.frame(Date = 1:5,  Ydet =1:5, Yobs = 2:6)

Ydet.obs_l <- Ydet.obs %>% pivot_longer(-Date )

ggplot(Ydet.obs_l ,aes(x = Date, y = value,colour = name)) geom_line()

Created on 2021-11-26 by the reprex package (v2.0.1)

  • Related