从包含格子向量的变量中绘制一系列

Plot a series from a variable containing a vector in lattice

首先:已经存在另一个标题几乎相同的问题 Plot a list of lines with R lattice package :但该问题的意图不同 - 每个列都需要一个单独的图。我需要的是一个单一的情节,其中包含一个包含叠加的每条线的系列。为此,一个有效的 hard-coded 列名称版本是:

library(lattice)
library(tibble)
cols = c('confirmed','recovered','exposed')

df = tibble( exposed= c(50,80,90), confirmed= c(10,20,30), recovered= c(3,5,7))
City1=df
Day = c(1:length(df))

Exposed=df$exposed
Confirmed=df$confirmed
Recovered=df$recovered
xyplot(Exposed + Confirmed + Recovered~ Day, main='City1 Stats',xlab='Day',ylab='Cases', 
cex.lab=0.6, xaxt="n", type = "l", auto.key = list(points = FALSE,lines = TRUE, 
  par.settings  = list(superpose.line = list(col = c("green","red","orange")))))

我宁愿发送一个列名向量而不是硬编码:该怎么做?它的形式类似于:

plotVars = c(Exposed, Confirmed, Recovered)
xyplot( plotVars ~ Day, main='City1 Stats',xlab='Day',ylab='Cases', 
  cex.lab=0.6, xaxt="n", type = "l", 
  auto.key = list(points = FALSE,lines = TRUE, 
  par.settings = list(superpose.line = list(col = c("green","red","orange")))))

如何才能使 plotVars 成为 xyplot 的可理解列表?

Update 从下面的答案中,建议使用 paste 设置列名,并以 + 作为分隔符。这是使用该方法的更新代码:

library(lattice)
cols = c('confirmed','recovered','exposed')

df = tibble( exposed= c(50,80,90), confirmed= c(10,20,30), recovered= c(3,5,7))
City1=df
Day = c(1:length(df))

exposed=df$exposed
confirmed=df$confirmed
recovered=df$recovered
fml = formula(paste(paste0(cols, collapse = " + "), "Day", sep = " ~ "))

xyplot(fml, main='City1 Stats',xlab='Day',ylab='Cases', cex.lab=0.6,
 xaxt="n", type = "l", auto.key = list(points = FALSE,lines = TRUE, 
 par.settings = list(superpose.line = list(col = c("green","red","orange")))))

这就是我之前评论的意思。可能有更好的方法来指定情节的公式,但我现在想不出更好的方法。

# packages
library(lattice)
library(tibble)

# data
df = tibble(
  exposed = c(50, 80, 90), 
  confirmed = c(10, 20, 30),
  recovered= c(3, 5, 7)
)
Day = seq_len(nrow(df))

# plot
plotVars = c("exposed", "confirmed", "recovered")

xyplot(
  formula(paste(paste0(plotVars, collapse = " + "), "Day", sep = " ~ ")), 
  data = df,
  main = 'City1 Stats',
  xlab = 'Day',
  ylab = 'Cases',
  cex.lab = 0.6,
  xaxt = "n",
  type = "l", 
  auto.key = list(
    points = FALSE, 
    lines = TRUE, 
    par.settings  = list(
      superpose.line = list(col = c("green","red","orange"))
    )
  )
)

reprex package (v0.3.0)

于 2020 年 3 月 5 日创建