I created a dataset with these variables. But Date variable should be the first 128 day of the year. My problems are:
- I could not convert the Date variable.
- How can I plot wheat, hazelnut and corn in time?
- How can I make subplot by repeating the previous plot with only two months data?
Can you help me please.
a <- 1
b <- 3
c <- 0
Date <- c(1:128)
Wheat <- rnorm(128, mean = a, sd = b)
Hazelnut <- runif(128, a ,b)
Corn <- rnorm(128, mean = c, sd = b)
df <- as.data.frame(cbind(Date, Wheat, Hazelnut, Corn))
df$Date <- as.Date(df$Date)
CodePudding user response:
How about this:
library(ggplot2)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>
#> date, intersect, setdiff, union
library(tidyr)
a <- 1
b <- 3
c <- 0
Date <- seq(ymd("2022-01-01"), ymd("2022-01-01") 127, by=1)
Wheat <- rnorm(128, mean = a, sd = b)
Hazelnut <- runif(128, a ,b)
Corn <- rnorm(128, mean = c, sd = b)
df <- data.frame(Date=Date,
Wheat=Wheat,
Hazelnut=Hazelnut,
Corn=Corn)
df <- df %>%
pivot_longer(c("Wheat", "Hazelnut", "Corn"),
names_to="crop",
values_to="vals")
ggplot(df, aes(x=Date, y=vals))
geom_line()
facet_wrap(~crop, ncol=1)
theme_classic()
df %>% filter(Date <= ymd("2022-02-28")) %>%
ggplot(aes(x=Date, y=vals))
geom_line()
facet_wrap(~crop, ncol=1)
theme_classic()
To create the plot only for two months, just subset the data in the code above, e.g.
matplot(dat[dat$Date < as.Date('2022-03-01'), -1], ...)
In case you want to create an actual time-series object, use ts
,
(df_ts <- ts(with(df, data.frame(Wheat, Hazelnut, Corn)), frequency=365,
start=2022))
# Time Series:
# Start = c(2022, 1)
# End = c(2022, 128)
# Frequency = 365
# Wheat Hazelnut Corn
# 2022.000 5.11287534 1.220670 0.75783511
# 2022.003 -0.69409451 2.079597 -3.88200740
# 2022.005 2.08938523 2.142468 -2.87751133
# 2022.008 2.89858781 2.237903 3.25732456
# [...]
# 2022.340 0.99453216 2.162396 -2.35466343
# 2022.342 -0.28477664 1.940185 0.49024896
# 2022.345 -0.84101482 1.730028 -3.71014271
# 2022.348 -5.07403354 1.560249 3.13762133
where
class(df_ts)
# [1] "mts" "ts" "matrix"
and plot
it.
plot(df_ts)