gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 19:39:32 24 4
gpt4 key购买 nike

我的最终目标是创建一个函数来轻松构建一系列 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$"alcohol"和 datatest$"quality"。那太愚蠢了。

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

最佳答案

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)

关于r - 使用两种方法调用 ggplot() 时出现美学错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60452446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com