【问题标题】:Aesthetics Error When Calling ggplot() Using Two Methods使用两种方法调用 ggplot() 时出现美学错误
【发布时间】:2020-02-28 13:09:45
【问题描述】:

我的最终目标是创建一个函数来轻松构建一系列 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"。太傻了。

有没有办法通过存储列名的变量名来访问数据?那将是我所需要的。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:
    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)
    

    【讨论】:

      【解决方案2】:

      您可以使用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))...,尽管没有您的数据来测试它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-28
        • 1970-01-01
        • 2012-02-20
        相关资源
        最近更新 更多