r-使用两种方法调用ggplot()时出现美学错误



我的最终目标是创建一个函数来轻松构建一系列ggplot对象。然而,在对我计划在函数中使用的一段代码进行一些测试时,我收到了一个geom_point美学错误,其原因似乎与我发现的其他错误实例不匹配。

低于的可复制代码

library(ggpubr)
library(ggplot2)
redData <- read.csv("http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv"
,header = TRUE, sep = ";")
datatest <- redData
x <- "alcohol"
y <- "quality"
#PlotTest fails with Error: geom_point requires the following missing aesthetics: x, y
PlotTest<-ggplot(datatest, aes(datatest$x,datatest$y)) +
geom_point()+xlim(0,15)+ylim(0,10)
#PlotTest2 works just fine, they should be functionally equivalent
PlotTest2 <- ggplot(redData, aes(redData$"alcohol", redData$"quality")) +
geom_point()+xlim(0,15)+ylim(0,10)
PlotTest
PlotTest2

PlotTest和PlotTest2在功能上应该是等效的,但它们显然不是,但我看不出是什么原因导致一个工作,而另一个不工作。

编辑

我现在意识到datatest$x,datatest$y实际上并没有下定决心去datatest$"酒精"和datatest$的"质量"。这太傻了。

是否有某种方法可以通过存储列名的变量名访问数据?那正是我所需要的。

library(ggpubr)
library(ggplot2)
redData <- read.csv("http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv" ,header = TRUE, sep = ";")
datatest <- redData
x <- "alcohol"
y <- "quality"
ggplot(datatest,aes(x=datatest[,x],y=datatest[,y]))+geom_point()+xlim(0,15)+ylim(0,10)+labs(x=x,y=y)
ggplot(redData,aes(x=alcohol,y=quality))+geom_point()+xlim(0,15)+ylim(0,10)

您可以使用aes_string(),它将字符变量作为参数名称:

library(dplyr)
library(ggplot2)
plot_cars <- function(data = mtcars, x, y) {
data %>% 
ggplot(aes_string(x, y)) +
geom_point()
}

plot_cars(x = "mpg", y = "cyl")

在上面的例子中,您会调用ggplot(redData, aes_string(x, y))...,但没有数据来测试它。

相关内容

最新更新