R/make_shot_chart.R

#' @title Makes Shot Chart Viz
#' @description Plots Shot Chart
#' @keywords NBA stat.nba.com
#' @import ggplot2
#' @import grid
#' @import viridis
#' @importFrom magrittr %>%
#' @export
#' @examples
#' make_shot_chart(curry_hex_df)

make_shot_chart <- function(hex_data_df, plot_title = '', sub = '', legend_title = '', color_var, my_font = 'Georgia') {

  courtURL <- "https://raw.githubusercontent.com/emilykuehler/basketballstatsR/master/data-raw/nba_court.jpg"
  court <- rasterGrob(jpeg::readJPEG(RCurl::getURLContent(courtURL)),
                      width=unit(1,"npc"), height=unit(1,"npc"))


  cols <- c('(-3%,3%)' = 'snow3', '(-6%,-3%)' = 'deepskyblue', '<-6%' = 'blue3', '(3%,6%)' = 'orange',
            '>6%' = 'red')
  shot_plot <- ggplot() +
    annotation_custom(court, -250, 250, -50, 420) +
    geom_polygon(aes(x=scaled_x, y=scaled_y, group=hex_id, fill=get(color_var)), data = hex_data_df) +
    coord_fixed() +
    scale_fill_manual(values = cols) +
    xlim(250, -250) +
    ylim(-50, 420) +
    geom_rug(alpha = 0.2) +
    labs(title = plot_title, subtitle = sub) +
    guides(fill=guide_legend(title=legend_title)) +
    theme(text = element_text(family = my_font),
          line = element_blank(),
          axis.title.x = element_blank(),
          axis.title.y = element_blank(),
          axis.text.x = element_blank(),
          axis.text.y = element_blank(),
          plot.title = element_text(size = 15, lineheight = 0.9, face = "bold"),
          legend.title = element_text(face = "bold"),
          legend.position = 'bottom')

  return(shot_plot)

}
emilykuehler/basketballstatsR documentation built on May 31, 2019, 10:01 a.m.