如何解决R-将圆添加到现有的时间序列图
我正在尝试在lattice
时间序列xyplot
的特定位置添加一个圆圈。我的情节是:
library(zoo)
library(lattice)
t <- structure(list(date = structure(c(18172,18177,18182,18187,18192,18202,18212,18217,18222,18237,18257,18267,18287,18322,18327,18332,18337,18342,18347,18357,18362,18367,18372,18377,18382,18392,18402,18407,18412,18432,18437,18447,18452,18457,18462,18467,18477,18482,18497,18502
),class = "Date"),t = c(0.22582148400414,0.256991369867836,0.20566669217573,0.197370049842565,0.277943312725968,0.409366098650766,0.485328298701375,0.265923063666776,0.193433942553932,0.146475290734094,0.261228272794155,0.287337189727423,0.431631481918686,0.555856286432998,0.500582779759492,0.406387635091313,0.270854099747563,0.327326988684063,0.302588934307361,0.249693446719906,0.305548452947743,0.397038410635602,0.439170248751657,0.46303881959878,0.488322795840136,0.509185404897871,0.55092532581109,0.551910236346757,0.591181074665548,0.648661902423056,0.430176528691085,0.405420937495388,0.437875812057808,0.391051426411378,0.375546279814988,0.397580900426823,0.3510990639662,0.196213067375209,0.188679707217845,0.190000000000123)),row.names = c(NA,-40L
),class = "data.frame")
ts <- read.zoo(t,format = "%Y-%m-%d")
xyplot(ts,col="darkgreen",lwd=2)
现在,我想添加一个以ts
的第12个元素为中心的圆。我可以分别绘制它(某种):
xyplot(ts[12][[1]] ~ ts[12],pch = 1,col = "red",cex=10)
但是当我尝试更新主图时,什么也没有发生:
p <- xyplot(ts,lwd=2)
## insert additional circle
update(p,panel = function(...) {
panel.xyplot(...)
panel.xyplot(ndvi_ts[12],ndvi_ts[12][[1]],pch=19,cex=10,col="red")
})
关于如何使它工作的任何想法?
解决方法
1)as.layer 像这样将第二个图定义为要添加到第一个图的层:
library(latticeExtra)
p1 <- xyplot(ts,col="darkgreen",lwd=2)
p2 <- xyplot(ts[12],type = "p",col = "red",cex = 10)
p1 + as.layer(p2)
2)层实现此目的的第二种方法是将layer
用于面板调用,而不是将as.layer
与网格对象一起使用。 p1
来自上方。
library(latticeExtra)
p1 + layer(panel.points(x[12],y[12],cex = 10))
3)trellis.focus 。第三种方法是使用trellis.focus
:。 p1
来自上方。
p1
trellis.focus()
panel.points(ts[12],cex = 12,col = "red")
trellis.unfocus()
4)更新面板问题中的代码已关闭,但第二个panel.xyplot
应该是panel.points
。 p1
来自上方。
update(p1,panel = function(...) {
panel.xyplot(...)
panel.points(ts[12],cex=10,col="red")
})
5)autoplot.zoo 这可以通过使用autoplot.zoo
的ggplot完成:
library(ggplot2)
autoplot.zoo(ts) +
geom_point(aes(x = time(ts)[12],y = ts[12]),pch = 1,cex = 10)
6)经典图形要使用经典图形:
plot(ts)
points(ts[12],cex = 10)
,
我建议您选择一种ggplot2
比lattice
更实用的方法。您可以对annotate()
geom的圆使用point
。这里的代码:
library(ggplot2)
#Code
ggplot(t,aes(x=date,y=t,group=1))+
geom_line(color='darkgreen',size=1)+
theme_bw()+
theme(panel.grid = element_blank())+
annotate(geom = 'point',x=t$date[12],y=t$t[12],size=25,shape=1,color="red")
输出:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。