【问题标题】:How to plot a sparse (with gaps) line with its segments colored according to some factor in R?如何绘制一条稀疏(有间隙)线,其线段根据 R 中的某些因素着色?
【发布时间】:2013-03-06 21:42:46
【问题描述】:

我有一个带有时间序列的data.frame。里面还有NAs,还有一个因素我想用它来突出一行的不同部分。

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)

但我尝试引入因子时无法摆脱连接线

xyplot(Discharge..cfs. ~ Timestamp, dat, type='l',
    groups=dat$Discharge..cfs..Quality, cex=0.5, auto.key=TRUE)

与 ggplot2 相同

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

我尝试了geom_line,但没有成功。我在ggplot2 mailing archive 中读到geom_path 是要走的路。但这对我来说不太管用。

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

【问题讨论】:

  • +1!因为你已经尝试过 ggplot2 和 lattice!可重复的示例和明确的问题。
  • Re:dots,为了正常工作,ggplot 必须对其参数进行一些花哨的评估,因此那里可能会出现问题。通常,无论如何清理列名都被认为是一种好习惯。例如,一个简单的gsub 删除点。

标签: r ggplot2 lattice


【解决方案1】:

问题在于分组。您可以使用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')

你得到:

编辑: 详细回答评论:只要不知道要分组的变量,就不能正确分组。如果您在一年中缺少几个月,那么这段代码当然会产生跳跃。在这种情况下,我建议这样做:

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')

你明白了:

【讨论】:

  • 这并不可靠。在这种情况下它可能会起作用。但如果一年内没有传感器的数据,那也无济于事。
  • 您总是必须知道要根据哪个变量进行分组。如果一年内有很大的差距,那么您必须分别获取月份和年份并将它们粘贴在一起作为grp
  • @mlt,可能替代(编辑)让您想到为一年内(或其他替代情况)内的缺失数据创建一个分组变量。
  • 我不知何故错过了this,所以看起来我只需使用groups=1就可以逃脱。嗯......它在上述示例的第二个想法上不起作用:(
  • 是的,group=1。它(总是)跳过我的脑海!很高兴你想出来了。我建议你把它写成答案并标记它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-30
  • 2019-07-10
  • 2018-07-15
相关资源
最近更新 更多