r-使用ggplot2,aes_string和重新排序使绘图功能 [英] r - make plotting function with ggplot2, aes_string and reorder

查看:249
本文介绍了r-使用ggplot2,aes_string和重新排序使绘图功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建将在内部使用 ggplot2 aes_string 重新排序,但到目前为止还没有运气。

I'm trying to make a function that will use ggplot2inside,aes_stringand reorder but with no luck so far.

基本上,如果我们有如下示例数据集:

Basically if we have a sample dataset like the following:

library(ggplot2)
library(dplyr)

set.seed(123)
dt <- data.frame(
          id = c(1,1,1,2,2),
          a = c("b", "d", "c", "a", "b"),
          b = sample(1:10, 5, replace = F),
          cat = c(1,1,2,2,2)) %>%
    mutate(a = as.factor(a)) %>% 
    as_tibble()

我想要函数接受以下参数:数据集,一个过滤变量和两个用于绘制的变量。

I want the function to accept the following arguments: the dataset, a filtering variable, and two variables for plotting.

这是我设法做到的:

myplot <- function(df, filtval, var1, var2) {
    data <- df %>% filter(id == filtval)

    ggplot(data) + 
        geom_point(
            aes_string(
                x = reorder(var1, var2),
                y = var2)
    )
}

不幸的是,它在运行时返回错误:

Unfortunately when running it returns the error:

myplot(dt, 1, "a", "b")
Warning message:
    In mean.default(X[[i]], ...) :
    argument is not numeric or logical: returning NA

这就是我想要的功能:

data <- dt %>% filter(id == 1)
ggplot(data) + 
    geom_col(aes(x = reorder(a, - b), y = b))


推荐答案

使用最新版本的ggplot,您应该与一起使用 aes !! sym()

With the latest version of ggplot, you should be use aes with !! and sym() to turn your strings into symbols.

myplot <- function(df, filtval, var1, var2) {
  data <- df %>% filter(id == filtval)

  ggplot(data) + 
    geom_point(
      aes(
        x = reorder(!!sym(var1), !!sym(var2)),
        y = !!sym(var2))
    )
}

这篇关于r-使用ggplot2,aes_string和重新排序使绘图功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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