如何使用变量在ggplot中指定列名

时间:2014-03-10 19:17:51

标签: r ggplot2 r-faq

我有一个ggplot命令

ggplot( rates.by.groups, aes(x=name, y=rate, colour=majr, group=majr) )

在一个函数内部。但我希望能够使用该函数的参数来挑选要用作颜色和组的列。即我想要这样的东西

f <- function( column ) {
    ...
    ggplot( rates.by.groups, aes(x=name, y=rate, colour= ??? , group=??? ) )
}

因此ggplot中使用的列由参数确定。例如。对于f(“majr”),我们得到了

的效果
ggplot( rates.by.groups, aes(x=name, y=rate, colour=majr, group=majr) )

但是对于f(“性别”),我们得到了

的效果
  ggplot( rates.by.groups, aes(x=name, y=rate, colour=gender, group=gender) )

我尝试过的一些事情:

ggplot( rates.by.groups, aes(x=name, y=rate, colour= columnName , group=columnName ) )

没用。也没有

e <- environment() 
ggplot( rates.by.groups, aes(x=name, y=rate, colour= columnName , group=columnName ), environment=e )

6 个答案:

答案 0 :(得分:103)

您可以使用aes_string

f <- function( column ) {
    ...
    ggplot( rates.by.groups, aes_string(x="name", y="rate", colour= column,
                                        group=column ) )
}

只要您将列作为字符串(f("majr")而不是f(majr))传递给函数。另请注意,我们将其他列"name""rate"更改为字符串。

如果由于某种原因您不想使用aes_string,您可以将其更改为(稍微麻烦一些):

    ggplot( rates.by.groups, aes(x=name, y=rate, colour= get(column),
                                        group=get(column) ) )

答案 1 :(得分:24)

来自ggplot2 V3.0.0的{​​{3}}:

  

aes()现在支持准引号,因此您可以使用!!,!!!和   :=。这将替换现在的aes_()和aes_string()   不推荐使用(但会保留很长时间)。

现在惯用的方法是使用ensym将变量包含的字符串转换为符号,然后使用!!取消引用

我们可以模拟OP的数据:

library(tidyverse)
rates.by.groups <- data.frame(
  name = LETTERS[1:3],
  rate = 1:3,
  mjr = LETTERS[c(4,4,5)],
  gender = c("M","F","F")
)

f <- function(column) {
  ggplot(rates.by.groups, 
         aes(x = name, 
             y = rate, 
             fill  = !!ensym(column), 
             group = !!ensym(column))) +
    geom_fill()
}

f("gender")
f("mjr")

如果我们希望将原始名称输入该函数,则可以执行以下操作:

f2 <- function(column) {
  column <- enquo(column)
  ggplot(rates.by.groups, 
         aes(x = name, 
             y = rate, 
             fill  = !!column, 
             group = !!column)) +
    geom_fill()
}

f2(gender)
f2(mjr)

答案 2 :(得分:12)

尝试使用aes_string代替aes

答案 3 :(得分:6)

另一种选择(ggplot2 > 3.0.0是使用整齐的评估代词.data来对rates.by.groups数据帧中选择的变量/列进行切片。

library(ggplot2)
theme_set(theme_classic(base_size = 14))

# created by @Moody_Mudskipper
rates.by.groups <- data.frame(
  name = LETTERS[1:3],
  rate = 1:3,
  mjr = LETTERS[c(4, 4, 5)],
  gender = c("M", "F", "F")
)

f1 <- function(df, column) {
  gg <- ggplot(df, 
         aes(x = name, 
             y = rate, 
             fill  = .data[[column]], 
             group = .data[[column]])) +
    geom_col() +
    labs(fill = column)
  return(gg)
}

plot_list <- lapply(list("gender", "mjr"), function(x){ f1(rates.by.groups, x) })
plot_list
#> [[1]]

#> 
#> [[2]]

# combine all plots
library(egg)
ggarrange(plots = plot_list,
          nrow = 2,
          labels = c('A)', 'B)'))

reprex package(v0.2.1.9000)于2019-04-04创建

答案 4 :(得分:4)

这是一种非常简单的方法!

执行以下两项操作:

  1. 使用sym()将列名转换为符号
  2. 在使用时添加!!

最小可复制示例:

my_col <- sym("Petal.Length")

iris %>% 
  ggplot(aes(x = Sepal.Length, y = !!my_col)) +
  geom_point()

答案 5 :(得分:1)

使用aes_string可以解决此问题,但是在添加错误栏geom_errorbar时确实会遇到问题。下面是一个简单的解决方案。

#Identify your variables using the names of your columns indie your dataset
 xaxis   <- "Independent"   
 yaxis   <- "Dependent"
 sd      <- "error"

#Specify error bar range (in 'a-b' not 'a'-'b')
 range   <- c(yaxis, sd)                                #using c(X, y) allows use of quotation marks inside formula
 yerrbar <- aes_string(ymin=paste(range, collapse='-'), 
                       ymax=paste(range, collapse='+'))


#Build the plot
  ggplot(data=Dataset, aes_string(x=xaxis, y=yaxis)) +
    geom_errorbar(mapping=yerrbar, width=15, colour="#73777a", size = 0.5) +
    geom_point   (shape=21)

奖金,您还可以使用ggplot中的以下行将小平面添加到绘图中:

facet_grid(formula(paste(Variable1, "~", Variable2)))

此脚本是根据以下原始帖子修改的:ggplot2 - Error bars using a custom function

相关问题