passing string to ggplot function

前端 未结 2 1403
自闭症患者
自闭症患者 2021-01-21 16:45

I would like to have a function that i could apply to any object that meets a criteria, and have a nice ggplot scatter plot with regression line print.

How

相关标签:
2条回答
  • 2021-01-21 16:52

    You can specify the columns using indexes.

    > library(ggplot2)
    > df <- data.frame(a = 1:10, b = 1:10, c=c("x"))
    > ggplot(data = df, aes(x = df[,1], y = df[,2])) + geom_line()
    
    0 讨论(0)
  • 2021-01-21 16:53

    Your function throws an error since aes() tries to evaluate the argument in the column names of your data. To be more specific, aes() tries to evaluate colnames(tempData)[1] as a column name and this column doesn't exist.

    To fix this, you somehow have to tell ggplot that you are not passing a column name, but an expression (a string) that will resolve to a column name.

    Use aes_string() for this. Concretely, simply replace aes() with aes_string(). Try this:

    PointReg <- function(Xts, a=1, b=2) {
      stopifnot(is.xts(Xts), 
                ncol(Xts) >1)
      tempData <- Xts[, c(a,b)]
      gPlot <- ggplot(data = tempData, 
                      aes_string(x = colnames(tempData)[1],
                          y = colnames(tempData)[2])) +
        geom_point(shape=1) +
        geom_smooth(method = lm)
      gPlot
    }
    

    enter image description here

    0 讨论(0)
提交回复
热议问题