【问题标题】:Ggplot code and function with a ggplot do not provide the same resultggplot 代码和带有 ggplot 的函数不提供相同的结果
【发布时间】:2021-07-16 17:11:57
【问题描述】:

我在创建包含 ggplot 的函数时遇到问题。当我在函数外执行代码时,它会生成我想要的情节,但在函数内它会生成不同的情节......我不确定我做错了什么......

我复制下面带有示例数据库的reprex:

library(tidyverse)
#> Warning: package 'tidyverse' was built under R version 4.0.5
#> Warning: package 'ggplot2' was built under R version 4.0.5
#> Warning: package 'tibble' was built under R version 4.0.5
#> Warning: package 'tidyr' was built under R version 4.0.5
#> Warning: package 'readr' was built under R version 4.0.5
#> Warning: package 'purrr' was built under R version 4.0.5
#> Warning: package 'dplyr' was built under R version 4.0.5
#> Warning: package 'stringr' was built under R version 4.0.5
#> Warning: package 'forcats' was built under R version 4.0.5
library(ggplot2)

# Example data 
wb <- data.frame(country = c("Antigua and Barbuda", "Belize", "Costa Rica", "Dominica", "Dominican Republic",
                             "El Salvador", "Guyana", "Guatemala", "Haiti", "Honduras", "Jamaica", "Nicaragua", 
                             "Panama", "Surinam", "Trinidad and Tobago"), 
                 income = factor(c("high", "low", "upper-middle","upper-middle", "upper-middle", 
                                   "lower-middle", "upper-middle", "upper-middle","low", NA, "upper-middle",
                                   "lower-middle", "high", "upper-middle", "high")),
                 group = c("A", "C", "B","C", "B","B", "B", "C","B", "A", "B","C", "C", "B", "A"),
                 stringsAsFactors = FALSE)


# I execute  the folowing code to create a plot (I do not execute it now because I do not have enough reputation in the forum to do it): 
df <- wb %>% 
  drop_na(income) %>%
  group_by(group,income) %>% 
  tally() %>% 
  complete(income, fill = list(n = 0)) %>% 
  mutate(percentage = n / sum(n) * 100)

ggplot(df, aes(income, percentage, fill = group)) + 
  geom_bar(stat = 'identity', position = 'dodge') +
  scale_y_continuous("Title Y", expand = c(0,0))+ 
  scale_x_discrete("Title X")+ 
  scale_fill_manual("Title of legend", values = c("#15607a", "#18a1cd", "cyan")) +
  theme_classic(base_size=11) + 
  theme(axis.text.x = element_text(angle = 0, 
                                   hjust = 1, vjust = 0),
        axis.line = element_blank(),
        axis.ticks.x = element_blank(), 
        legend.title = element_text(colour = "#00344c", size = 8, face = "bold")) 
# Now I try to create a function to automatize the previous plot 

create_graph <- function(x,y,t){
  df <- wb %>% 
    drop_na({{y}}) %>%
    group_by({{x}},{{y}}) %>% 
    tally() %>% 
    complete({{y}}, fill = list(n = 0)) %>% 
    mutate(percentage = n / sum(n) * 100)
  
  ggplot(df, aes(y, percentage, fill = x)) + 
    geom_bar(stat = 'identity', position = 'dodge') +
    scale_y_continuous("Title Y", expand = c(0,0))+ 
    scale_x_discrete(t)+ 
    scale_fill_manual("Title of legend", values = c("#15607a", "#18a1cd", "cyan")) +
    theme_classic(base_size=11) + 
    theme(axis.text.x = element_text(angle = 0, 
                                     hjust = 1, vjust = 0),
          axis.line = element_blank(),
          axis.ticks.x = element_blank(), 
          legend.title = element_text(colour = "#00344c", size = 8, face = "bold")) 
}

# When I execute the function alone, the resulting plot it's not the same as the plot coded above: 
create_graph(x = "income", 
             y = "group",
             t = "Funny title")

reprex package (v2.0.0) 于 2021-04-22 创建

非常感谢!

【问题讨论】:

    标签: r function ggplot2 plot bar-chart


    【解决方案1】:

    几个观察:

    • create_graph() 调用中,如果您使用 curly-curly {{..}} 包装器进行非标准评估,则无需引用变量名。
    • create_graph() 函数中,我认为您可能已经相对于示例图交换了一些 xys。
    • aes(...) 调用中,您还可以使用 curly-curly 包装器。

    以下是我如何获得函数以返回示例图作为示例:

    library(tidyverse)
    library(ggplot2)
    
    # Example data 
    wb <- data.frame(country = c("Antigua and Barbuda", "Belize", "Costa Rica", "Dominica", "Dominican Republic",
                                 "El Salvador", "Guyana", "Guatemala", "Haiti", "Honduras", "Jamaica", "Nicaragua", 
                                 "Panama", "Surinam", "Trinidad and Tobago"), 
                     income = factor(c("high", "low", "upper-middle","upper-middle", "upper-middle", 
                                       "lower-middle", "upper-middle", "upper-middle","low", NA, "upper-middle",
                                       "lower-middle", "high", "upper-middle", "high")),
                     group = c("A", "C", "B","C", "B","B", "B", "C","B", "A", "B","C", "C", "B", "A"),
                     stringsAsFactors = FALSE)
    
    create_graph <- function(x,y,t){
      df <- wb %>% 
        drop_na({{x}}) %>%
        group_by({{y}},{{x}}) %>% 
        tally() %>% 
        complete({{x}}, fill = list(n = 0)) %>% 
        mutate(percentage = n / sum(n) * 100)
      
      ggplot(df, aes({{x}}, percentage, fill = {{y}})) + 
        geom_bar(stat = 'identity', position = 'dodge') +
        scale_y_continuous("Title Y", expand = c(0,0))+ 
        scale_x_discrete(t)+ 
        scale_fill_manual("Title of legend", values = c("#15607a", "#18a1cd", "cyan")) +
        theme_classic(base_size=11) + 
        theme(axis.text.x = element_text(angle = 0, 
                                         hjust = 1, vjust = 0),
              axis.line = element_blank(),
              axis.ticks.x = element_blank(), 
              legend.title = element_text(colour = "#00344c", size = 8, face = "bold")) 
    }
    
    create_graph(x = income, 
                 y = group,
                 t = "Funny title")
    

    reprex package (v1.0.0) 于 2021 年 4 月 22 日创建

    旁注:如果您将第二个参数命名为 y,人们可能会认为 y 是出现在 y 轴上的内容,而您的绘图中并非如此。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      • 1970-01-01
      • 2013-06-28
      • 1970-01-01
      相关资源
      最近更新 更多