0

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
1
  • 1
    Can you please post dataset in a way, we can use it. Try function dput(Ydet.obs) and copy the output as code to your question. Commented Nov 25, 2021 at 21:13

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer worked, thank you
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.