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

发布于 2025-01-09 00:31:22 字数 901 浏览 0 评论 0原文

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

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

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("gender") 我们得到的效果是

  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 )

I have a ggplot command

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

inside a function. But I would like to be able to use a parameter of the function to pick out the column to use as colour and group. I.e. I would like something like this

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

So that the column used in the ggplot is determined by the parameter. E.g. for f("majr") we get the effect of

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

but for f("gender") we get the effect of

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

Some things I tried:

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

did not work. Nor did

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

顾挽 2025-01-16 00:31:22

注意:此答案中的解决方案是“soft-deprecated”。请使用 .data[[ 查看当前首选方法的答案。

您可以使用 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) ) )

Note: the solution in this answer is "soft-deprecated". See the answer below using .data[[ for the currently preferred method.

You can use aes_string:

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

as long as you pass the column to the function as a string (f("majr") rather than f(majr)). Also note that we changed the other columns, "name" and "rate", to be strings.

If for whatever reason you'd rather not use aes_string, you could change it to (the somewhat more cumbersome):

    ggplot( rates.by.groups, aes(x=name, y=rate, colour= get(column),
                                        group=get(column) ) )
池予 2025-01-16 00:31:22

来自ggplot2 V3.0.0发行说明 >:

aes() 现在支持准引用,以便您可以使用 !!、!!! 和
:=。这取代了现在的 aes_() 和 aes_string()
软弃用(但会保留很长一段时间)。

现在惯用的方法是使用 sym() 将变量包含的字符串转换为符号(这与基本别名 as.name() 几乎相同) / as.symbol()),并使用 !! 取消引用它

模拟 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) {
  column <- sym(column)
  ggplot(rates.by.groups, 
         aes(x = name, 
             y = rate, 
             fill  = !!column, 
             group = !!column)) +
    geom_col()
}

f("gender")
f("mjr")
x <- "gender"
f(x)

如果我们宁愿将原始名称提供给函数,我们可以这样做:

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

它将与名称(又名符号)和字符串一起使用正如

f2(gender)
f2(mjr)
f2("gender")
f2("mjr")

Lionel 关于 ensym() 所说:

它的目的是模仿参数的语法,您可以同时提供两者
在 LHS 中,例如 list(bare = 1, "quoted" = 2)


关于 enquo() 的注释

enquo() 引用表达式(不一定是符号)对于参数,它不会像 ensym() 那样将字符串文字转换为符号,因此这里可能不太适合,但我们可以这样做:

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

f3(gender)
f2(mjr)

From the release notes of ggplot2 V3.0.0 :

aes() now supports quasiquotation so that you can use !!, !!!, and
:=. This replaces aes_() and aes_string() which are now
soft-deprecated (but will remain around for a long time).

The idiomatic way now would be to convert to a symbol the string that the variable contains, using sym()(which is almost the same as base aliases as.name() / as.symbol()), and unquote it using !!

Simulating OP's data we can do :

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) {
  column <- sym(column)
  ggplot(rates.by.groups, 
         aes(x = name, 
             y = rate, 
             fill  = !!column, 
             group = !!column)) +
    geom_col()
}

f("gender")
f("mjr")
x <- "gender"
f(x)

If we'd rather feed raw names to the function we can do:

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

It will work with names a.k.a. symbols AND with string literals

f2(gender)
f2(mjr)
f2("gender")
f2("mjr")

As Lionel says about ensym():

it's meant to mimic the syntax of arguments where you can supply both
in the LHS, e.g. list(bare = 1, "quoted" = 2)


A note on enquo()

enquo()quotes the expression (not necessarily a symbol) fed to the argument, it doesn't convert a string literal to a symbol as ensym() does so it might be less adapted here, but we can do :

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

f3(gender)
f2(mjr)
染火枫林 2025-01-16 00:31:22

另一种选择(ggplot2 > 3.0.0)是使用整洁的评估代词.datarates.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 包于 2019 年 4 月 4 日创建(v0.2.1.9000 )

Another option (ggplot2 > 3.0.0) is to use the tidy evaluation pronoun .data to slice the chosen variable/column from the rates.by.groups data frame.

See also this answer

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)'))

Created on 2019-04-04 by the reprex package (v0.2.1.9000)

内心激荡 2025-01-16 00:31:22

尝试使用 aes_string 而不是 aes

Try using aes_string instead of aes.

一笑百媚生 2025-01-16 00:31:22

做两件事

  1. 使用 sym() 将列名转换为符号
  2. 当您想要使用它时,在符号前添加 !!

示例

my_col <- sym("Petal.Length")

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

Do two things

  1. Turn the column name into a symbol with sym()
  2. Prepend !! to the symbol when you want to use it

Example

my_col <- sym("Petal.Length")

iris %>% 
  ggplot(aes(x = Sepal.Length, y = !!my_col)) +
  geom_point()
旧人哭 2025-01-16 00:31:22

使用 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 - 使用自定义函数的误差线

Using aes_string does fix this problem, but does face an issue when adding error bars geom_errorbar. Below is a simple solution.

#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)

Bonus, you can also add facets to your plot using these lines inside the ggplot:

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

This script was modified from this original post: ggplot2 - Error bars using a custom function

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文