gpt4 book ai didi

r - 如何根据 R 中的某个因素绘制一条稀疏(带间隙)线,其线段着色?

转载 作者:行者123 更新时间:2023-12-04 21:19:34 24 4
gpt4 key购买 nike

我有一个 data.frame与时间序列。还有NA s 以及我想用一个因素来突出显示一条线的不同部分。

flow.mndnr <- function(id, start, end) {
uri <- sprintf("http://maps1.dnr.state.mn.us/cgi-bin/csg.pl?mode=dump_hydro_data_as_csv&site=%s&startdate=%s&enddate=%s", id, start, end)
dat <- read.csv(url(uri), colClasses=c(Timestamp="Date"))
rng <- range(dat$Timestamp)
d <- data.frame(Timestamp=seq(rng[1], rng[2], by='day'))
merge(d, dat, all.x=TRUE)
}
dat <- flow.mndnr("28062001", as.Date("2002-04-02"), as.Date("2011-10-05"))

我可以无条件地绘制它
library(lattice)
xyplot(Discharge..cfs. ~ Timestamp, dat, type='l', cex=0.5, auto.key=TRUE)

enter image description here

但是当我尝试引入因子时,我无法摆脱连接线
xyplot(Discharge..cfs. ~ Timestamp, dat, type='l',
groups=dat$Discharge..cfs..Quality, cex=0.5, auto.key=TRUE)

enter image description here

与 ggplot2 相同
dat$quality <- dat$Discharge..cfs..Quality
ggplot(dat, aes(x=Timestamp, y=Discharge..cfs.)) +
geom_path(aes(colour=quality)) + theme(legend.position='bottom')

enter image description here

我试过 geom_line没有成功。我读了 ggplot2 mailing archive那个 geom_path是要走的路。但这对我来说并不完全有效。

附言为什么 ggplot2 不喜欢名称中的点,所以我不得不使用另一个点?

最佳答案

问题出在分组上。您可以使用 year跳过这些跳跃。做就是了:

dat$grp <- format(dat$Timestamp, "%Y")
ggplot(dat, aes(x=Timestamp, y=Discharge..cfs.)) +
geom_path(aes(colour = quality, group = grp)) +
theme(legend.position='bottom')

你得到:

enter image description here

编辑:详细回答评论:只要不知道按哪个变量分组,就无法正确分组。如果你在一年中缺少几个月,当然这段代码会产生跳跃。在这种情况下,我建议做这样的事情:
dat$grp <- paste(format(dat$Timestamp, "%Y"), format(dat$Timestamp, "%m"))
ggplot(dat, aes(x=Timestamp, y=Discharge..cfs.)) +
geom_path(aes(colour = quality, group = grp)) +
theme(legend.position='bottom')

你得到这个:

enter image description here

关于r - 如何根据 R 中的某个因素绘制一条稀疏(带间隙)线,其线段着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15258656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com