我想将带引号的字符串传递给调用ggplot2的函数。
library(magrittr); library(ggplot2)
g1 <- function( variable ) {
ggplot(mtcars, aes_string("wt", variable, size="carb")) +
geom_point()
}
g1("mpg")
Run Code Online (Sandbox Code Playgroud)
这很好用,但是v3.1.0文档提倡准引用和NSE aes()。
所有这些功能均已弃用。请改用整洁的评估习惯用法(请参阅aes()文档中的准引用部分)。
但是这些aes()示例使用NSE(即,g1(mpg)而不是g1("mpg"))。同样,这些SO解决方案使用NSE值或aes_()/ aes_string()。
我希望该函数接受SE /引号字符串,以容纳字符向量,例如:
variables <- c("mpg", "cyl", "disp")
variables %>%
lapply(g1)
Run Code Online (Sandbox Code Playgroud) 我正在开发一个闪亮的应用程序,用户可以在其中选择使用 ggplot2 绘制哪些变量,但是我完全不确定将字符串(要绘制的变量的名称)转换为合适的函数参数的最佳方法。
考虑以下非常人为的工作示例:
df <- data.frame(gp = factor(rep(letters[1:3], each = 10)),
y = rnorm(30))
ggplot(df, aes(x = gp, y = y)) +
geom_point() + facet_wrap(~gp)
Run Code Online (Sandbox Code Playgroud)
现在,如果我只有变量名称的字符串,我将如何告诉 ggplot 在 x 轴上绘制“gp”变量?
我提出了以下内容,但有没有更简单、更传统的方法?请注意我在 aes() 和 facet_wrap() 函数中使用的不同方法。
x.var <- "gp"
ggplot(df, aes(x=lol <- switch(x.var,"gp"=gp), y = y)) +
geom_point() + facet_wrap(as.formula(paste("~",x.var)))
Run Code Online (Sandbox Code Playgroud)
任何见解都非常感谢!
我的数据DT具有以下结构:
structure(list(Ticker = c("MSDLWI Index", "MSDLWI Index", "MSDLWI Index", "MSDLWI Index","MSDLWI Index", "MSDLWI Index", "NDLEACWF Index", "NDLEACWF Index", "NDLEACWF Index","NDLEACWF Index", "NDLEACWF Index", "NDLEACWF Index"), Date = structure(c(-1L, 89L, 180L, 272L, 364L, 454L, 15705L, 15793L, 15884L, 15978L, 16070L, 16136L), class = c("IDate", "Date")), Value = c(NA, -0.02925, -0.180118465104301, 0.124488001005151, 0.0497217814923236,0.0966385660152425, 0.0323951658690891, 0.0842289682913797, 0.00992717655157427, 0.0631103139013451, 0.0782204344979787, 0.00855027196875335)), .Names =c("Ticker", "Date", "Value"), row.names = c(NA, -12L),class=c("data.table","data.frame"))
Run Code Online (Sandbox Code Playgroud)
头(DT,3)
Ticker Date Value
1: MSDLWI Index 1969-12-31 NA
2: MSDLWI Index 1970-03-31 -0.0292500 …Run Code Online (Sandbox Code Playgroud) 我正在用 ggplot 构建一个图,但我事先不知道 y 列的名称。相反,y 列的名称包含在变量 yname 中。这显然不起作用:
ggplot(df, aes(x=date, y=yname))
Run Code Online (Sandbox Code Playgroud)
因为 ggplot 在 df 中查找字面上名为“yname”的列。如何将 y 列的名称作为变量传递给 ggplot?
我用来ggplot生成带有拟合线的散点图,如下所示
ggplot(df, aes(x=colNameX, y=colNameY)) +
geom_point() +
geom_smooth(method=loess, se=T, fullrange=F, size=1) + ylim(0,5)
Run Code Online (Sandbox Code Playgroud)
鉴于此,想要将上面概括为一个采用以下参数的函数
scatterWithRegLine = function(df, xColName, yColName, regMethod, showSe, showFullrange, size, yAxisLim) {
# How should I use the variables passed into the function above within ggplot
}
Run Code Online (Sandbox Code Playgroud)
这样我就可以按如下方式调用该函数
scatterWithRegLine(df, "mpg", "wt", "loess", TRUE, FALSE, 1, c(0,5))
Run Code Online (Sandbox Code Playgroud)