我想制造日期與的線圖Ydet,并Yobs在ggplot,我都試過了,但無法實作它。請問有人可以幫忙嗎?
> 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
uj5u.com熱心網友回復:
有幾種方法,但這里有一個簡單的:
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)
uj5u.com熱心網友回復:
ggplot 確實是為處理“整潔”或長資料幀而設計的,因此請先轉換您的資料。
(見https://r4ds.had.co.nz/tidy-data.html)
我編造了高度簡化的資料,因為您的資料無法重現。請參閱有關制作可重復資料以供將來提問的帖子: 如何制作出色的 R 可重復示例
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()

由reprex 包(v2.0.1)于 2021 年 11 月 26 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/366450.html
上一篇:對齊多行“膠水”運算式
