修改函数后的ggplot:二元运算符错误的非数字参数

时间:2017-09-15 16:37:55

标签: r function ggplot2 dplyr

我试图从函数中生成一个ggplot。我可以使用下面的示例数据和代码来完成。

  • 如果我在函数之外生成图(p),我可以毫无问题地修改它,添加标题,副标题,轴标签等(例如p + labs(title = "Most frequent words, by gender"))。
  • 但是,如果我从函数中生成绘图然后尝试修改它,我会收到以下错误:non-numeric argument to binary operator.
  • 在这两种情况下,对象“p”都显示在“值”下。

我当然想要使用一个函数,因为我有许多不同的group_by变量来测试,我想消除输入错误(例如,在以后的分析中忘记将“性别”改为“收入”)。

有人可以解释为什么只有在修改函数中创建的ggplot后才会出现错误?当然,我很感激有关如何消除错误来源的建议。

# sample data of favorite activities
df <- tibble(
  word = c("walk","hike","garden","garden","walk","hike", "garden","hike","hike","hike","walk"),
  gender = c("Male","Female","Female","Female","Male","Male","Male", "Male","Male","Female","Female")
)
df

# function to figure out the proportions of the activities
sum_text_prop <- function(df, groupbyvar) {
  groupbyvar <- enquo(groupbyvar)
  df %>% 
    count(!!groupbyvar, word, sort = TRUE) %>% 
    group_by(groupbyvar = !!groupbyvar) %>% 
    mutate(proportion = n / sum(n)) %>% 
  top_n(proportion, n = 5) %>%
  ungroup()
}

# function to plot the most common words
plot_text_prop <- function(df) {
  p <- ggplot(data = df, aes(x = word, y = proportion, fill = groupbyvar)) +
  geom_bar(stat = "identity", alpha = 0.8, show.legend = FALSE) +
  facet_wrap(~ groupbyvar, ncol = 2, scales = "free") +
  coord_flip()

  print(p)
}

# deploy the functions
df %>% 
  sum_text_prop(groupbyvar = gender) %>% 
  plot_text_prop()

# add a title to the plot
p + labs(title = "Most frequent words, by gender")

# error: Error in p + labs(title = "Most frequent words, by gender") : 
  non-numeric argument to binary operator

更新

感谢有用的回复,我修改后的代码如下:

plot_text_prop <- function(df) {
  ggplot(data = df, aes(reorder_within(word, proportion, groupbyvar),
                         proportion, fill = groupbyvar)) +
  geom_bar(stat = "identity", alpha = 0.8, show.legend = FALSE) +
  scale_x_reordered() +
  facet_wrap(~ groupbyvar, ncol = 2, scales = "free") +
  coord_flip()
}

p <- tidy_infl %>% 
  sum_text_prop(groupbyvar = gender) %>% 
  plot_text_prop()

p + labs(title = "Most frequent words, by gender") 

0 个答案:

没有答案