[英]Apply column names to legend in a function
我正在编写一个函数,该函数接受两个变量(理想情况下是来自同一数据帧的列)并绘制它们。 该图还将使用来自列的名称来包含图例,这就是我遇到的困难。
下面的代码尽可能地接近期望的结果。 我只对使用基数R感兴趣。
plotpairs <- function(x,y){
plot(x, type = "l", col = "red")
lines(y, type = "l", col = "blue")
legend(0,ylim_max, legend = paste0(x, y), lwd = c(5,5), col = c("red", "blue"), bty = "n")
}
plotpairs(df$F3, df$F4)
如果提供data.frame
或matrix
作为参数,则可以使用colnames()
提取列名称,否则必须使用deparse(substitute())
或match.call()
如我在此使用的那样。
set.seed(1)
F3 <- cumsum(runif(1e3, -2, 2))+runif(1e3)
F4 <- cumsum(rnorm(1e3))+rnorm(1e3, 0, 0.5)
df <- data.frame(F3, F4)
plotpairs <- function(x, y) {
if (NCOL(x) > 1) {
nam <- colnames(x)[1:2]
y <- x[,2]
x <- x[,1]
} else {
nam <- as.character(match.call()[c("x", "y")])
}
plot(x, type="l", col="red", ylim=range(c(x, y)))
lines(y, type="l", col="blue")
legend("topleft", legend=nam, lwd=c(5, 5), col=c("red", "blue"), bty="n")
}
plotpairs(F3, F4)
with(df, plotpairs(F3, F4)) # same
plotpairs(df) # same
这将从作为第一个参数给出的数据框中绘制指示的列,或者如果未给出名称,则将绘制前两列。 请注意,我们首先使用type = "n"
一起绘制两个图,以确保将图设置得足够大以容纳两个变量。 该示例使用内置的数据帧trees
。
plotpairs <- function(data, name1 = names(data)[1], name2 = names(data)[2]) {
both <- c(data[[name1]], data[[name2]])
plot(seq_along(both) / 2, both, type = "n", xlab = "", ylab = "")
lines(data[[name1]], type = "l", col = "red")
lines(data[[name2]], type = "l", col = "blue")
legend("topleft", legend = c(name1, name2), lwd = 5,
col = c("red", "blue"), bty = "n")
}
plotpairs(trees, "Girth", "Volume")
我还根据包含正则表达式的@Rui Barradas注释得出了答案。 由于我将使用“ df $ F3”之类的输入,因此我可以指望出现“ $”符号,尽管这可能会限制代码的灵活性。
plotpairs <- function(x,y){
xnam <- deparse(substitute(x))
ynam <- deparse(substitute(y))
xnam1 <- substring(xnam, regexpr("[$]", xnam)+1)
ynam1 <- substring(ynam, regexpr("[$]", ynam)+1)
plot(x, type = "l", col = "red")
lines(y, type = "l", col = "blue")
legend("topleft", legend = c(paste0(xnam1), paste0(ynam1)),lwd = c(5,5), col = c("red", "blue"), bty = "n")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.