【发布时间】:2020-03-06 17:18:33
【问题描述】:
首先:确实已经存在另一个标题几乎相同的问题Plot a list of lines with R lattice package:但这个问题的意图是不同的——一个人想要为每一列单独绘制一个图。我需要的是一个单一的情节,其中包含一系列叠加的每条线。为此,一个有效的硬编码列名版本是:
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 的可理解列表?
更新从下面的答案建议是使用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")))))
【问题讨论】:
-
您可以指定 vars 的字符向量,然后将它们粘贴到 xyplot 中以创建公式对象吗?如果是这样,我可以创建一个更详细的答案。
-
@agila 是的:即使看起来有点牵涉,逻辑也可以隐藏在一个编写一次并提供所需功能的函数中。请提出一个答案