将字符串传递给ggplot函数 [英] passing string to ggplot function

查看:120
本文介绍了将字符串传递给ggplot函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个函数可以应用于符合条件的任何对象,并且有一个带回归线打印的 ggplot 散点图。然而,我不能用代码概括我可以在 REPL 上做什么。



所以我有这个工作:

  require(ggplot2)
require(xts)
set.seed(1)
dd = xts(cbind(rnorm(10),runif(10)),order.by = Sys.Date()+ 1: 10)
名称(dd)< -c('d1','d2')

gp< - ggplot(data = dd,
aes(x = d1 ,y = d2))+
geom_point(shape = 1)+
geom_smooth(method = lm)

但是这失败了
$ b $ pre $ PointReg < - 函数(Xts,a = 1,b = 2) {
stopifnot(is.xts(Xts),
ncol(Xts)> 1)
tempData <-Xts [,c(a,b)]
gPlot< ; - ggplot(data = tempData,
aes(x = colnames(tempData)[1],
y = colnames(tempData)[2]))+
geom_point(shape = 1)+
geom_smooth(method = lm)
gPlot
}

什么我做错了吗?

解决方案 您的函数会抛出一个错误,因为 aes()尝试评估数据列名中的参数。更具体地说, aes()会尝试评估 colnames(tempData)[1] 作为列名,列不存在。



为了解决这个问题,你必须告诉 ggplot 你没有通过列名称,而是一个将解析为列名的表达式(字符串)。



使用 aes_string()为了这。具体来说,只需用 aes_string()替换 aes()即可。试试这个:

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


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.

However, i cannot generalise what i can do at the REPL with code.

so i have this working:

require(ggplot2)    
require(xts)
set.seed(1)
dd = xts(cbind(rnorm(10), runif(10)), order.by = Sys.Date() + 1:10)
names(dd) <- c('d1', 'd2')

gp <- ggplot(data = dd, 
             aes(x = d1, y = d2)) + 
        geom_point(shape=1) + 
        geom_smooth(method = lm)

But this fails

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

What am i doing wrong?

解决方案

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
}

这篇关于将字符串传递给ggplot函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆