[英]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.