Pxanalyst
Pxanalyst

Reputation: 43

How to make a ggplot statement into a function

I am currently trying to write the following ggplot code into a function that I can store and re-use for similar data sets. However I am having trouble figuring out how out how to write this and include the facet_wrap condition

Below is my current code with no function

df <- data.frame (pre_post  = c("pre", "post","pre","post","pre","post","pre","post"),
              team = c("Lakers", "Lakers","Miami Heat","Miami Heat","Celtics","Celtics","Warriors","Warriors"),
              median_score_time = c("3", "2","5","7","9","8","2","3"),
              total_plays= c("105","134","90","124","97","106","131","121"))


df %>% ggplot(aes(
  fill=pre_post,
  x=pre_post,
  y=median_score_time,
  label=paste0(median_score_time, "\n(n=",total_plays,")")
)) +
  geom_col(width=0.5) +
  geom_text(vjust=-0.2, size=3) +
  ylab("Median_Minutes_To_Score") +
  xlab("") +
  facet_wrap(~team)

Upvotes: 1

Views: 206

Answers (1)

Vin&#237;cius F&#233;lix
Vin&#237;cius F&#233;lix

Reputation: 8836

Here a way to implement functions with dplyr and ggplot2

df <-
  data.frame(
    pre_post  = c("pre", "post","pre","post","pre","post","pre","post"),
    team = c("Lakers", "Lakers","Miami Heat","Miami Heat","Celtics","Celtics","Warriors","Warriors"),
    median_score_time = c("3", "2","5","7","9","8","2","3"),
    total_plays= c("105","134","90","124","97","106","131","121")
    )

library(ggplot2)
library(dplyr)

plot_func <-
  function(data,x_var,y_var,fill_var,lbl_var,fct_var){
    data %>%
      ggplot(aes(
      fill={{fill_var}},
      x={{x_var}},
      y={{y_var}},
      label=paste0({{y_var}}, "\n(n=",{{lbl_var}},")")
    )) +
      geom_col(width=0.5) +
      geom_text(vjust=-0.2, size=3) +
      ylab("Median_Minutes_To_Score") +
      xlab("") +
      facet_wrap(facets = vars({{fct_var}}))
}

plot_func(
  data = df,
  x_var = pre_post,
  y_var = median_score_time,
  fill_var = pre_post,
  lbl_var = total_plays,
  fct_var = team
    )

enter image description here

Upvotes: 1

Related Questions