document.write('
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. library(argparse)
  2. library(rjson)
  3. library(ggplot2)
  4. library(grid)
  5. library(gridExtra)
  6. library(png)
  7. library(jpeg)
  8. library(RCurl)
  9. library(hexbin)
  10. library(plyr)
  11.  
  12. # create parser object
  13. parser <- ArgumentParser()
  14. # specify our desired options
  15. # by default ArgumentParser will add an help option
  16. parser$add_argument("--player", action=\'store\', default=\'Stephen Curry\', help=\'Player name\')
  17. # get command line options, if help option encountered print help and exit,
  18. # otherwise if options not found on command line then set defaults,
  19. args <- parser$parse_args()
  20. url <- \'https://raw.githubusercontent.com/Maiae/NBA-Shot-Charts/master/players.csv\'
  21. print(args$player)
  22. players <- read.csv(url, header=TRUE, stringsAsFactor=FALSE)
  23. playerID <- as.numeric(players[players[,2] == args$player, 1])
  24. # shot data for specified player
  25. #playerID <- 201939
  26. shotURL <- paste("http://stats.nba.com/stats/shotchartdetail?CFID=33&CFPARAMS=2014-15&ContextFilter=&ContextMeasure=FGA&DateFrom=&DateTo=&GameID=&GameSegment=&LastNGames=0&LeagueID=00&Location=&MeasureType=Base&Month=0&OpponentTeamID=0&Outcome=&PaceAdjust=N&PerMode=PerGame&Period=0&PlayerID=",playerID,"&PlusMinus=N&Position=&Rank=N&RookieYear=&Season=2014-15&SeasonSegment=&SeasonType=Regular+Season&TeamID=0&VsConference=&VsDivision=&mode=Advanced&showDetails=0&showShots=1&showZones=0", sep = "")
  27.  
  28. # import from JSON
  29. shotData <- fromJSON(file = shotURL, method="C")
  30.  
  31. # unlist shot data, save into a data frame
  32. shotDataf <- data.frame(matrix(unlist(shotData$resultSets[[1]][[3]]), ncol=21, byrow = TRUE))
  33. print(head(shotDataf))
  34.  
  35. # shot data headers
  36. colnames(shotDataf) <- shotData$resultSets[[1]][[2]]
  37.  
  38. # covert x and y coordinates into numeric
  39. shotDataf$LOC_X <- as.numeric(as.character(shotDataf$LOC_X))
  40. shotDataf$LOC_Y <- as.numeric(as.character(shotDataf$LOC_Y))
  41. shotDataf$SHOT_DISTANCE <- as.numeric(as.character(shotDataf$SHOT_DISTANCE))
  42.  
  43. ## start plots
  44. # simple plot using EVENT_TYPE to colour the dots
  45. ggplot(shotDataf, aes(x=LOC_X, y=LOC_Y)) +
  46.          geom_point(aes(colour = EVENT_TYPE))
  47.  
  48.  
  49.  
  50. # half court image
  51. courtImg.URL <- "http://lookingforamerica.us/wp-content/uploads/2015/03/Nba-Basketball-Court-Dimensions.jpg"
  52. court <- rasterGrob(readJPEG(getURLContent(courtImg.URL)),
  53.            width=unit(1,"npc"), height=unit(1,"npc"))
  54.  
  55. # plot using NBA court background and colour by shot zone
  56. ggplot(shotDataf, aes(x=LOC_X, y=LOC_Y)) +
  57.       annotation_custom(court, -250, 250, -50, 420) +
  58.       geom_point(aes(colour = SHOT_ZONE_BASIC, shape = EVENT_TYPE)) +
  59.       xlim(-250, 250) +
  60.       ylim(-50, 420)
  61.  
  62.  
  63.  
  64. # plot using ggplot and NBA court background image, flip x axis
  65. ggplot(shotDataf, aes(x=LOC_X, y=LOC_Y)) +
  66.        annotation_custom(court, -250, 250, -50, 420) +
  67.        geom_point(aes(colour = SHOT_ZONE_BASIC, shape = EVENT_TYPE)) +
  68.        xlim(250, -250) +
  69.        ylim(-50, 420) +
  70.        geom_rug(alpha = 0.2) +
  71.        coord_fixed() +
  72.        ggtitle(paste("Shot Chart\\n", unique(shotDataf$PLAYER_NAME), sep = "")) +
  73.        theme(line = element_blank(),
  74.              axis.title.x = element_blank(),
  75.              axis.title.y = element_blank(),
  76.              axis.text.x = element_blank(),
  77.              axis.text.y = element_blank(),
  78.              legend.title = element_blank(),
  79.              plot.title = element_text(size = 15, lineheight = 0.9, face = "bold"))
  80.  
  81.  
  82.  
  83. # scrape player photo and save as a raster object
  84. playerImg.URL <- paste("http://stats.nba.com/media/players/132x132/",playerID,".png", sep="")
  85. playerImg <- rasterGrob(readPNG(getURLContent(playerImg.URL)),
  86.                                                     width=unit(0.15, "npc"), height=unit(0.15, "npc"))
  87.  
  88. # plot using ggplot and NBA court background
  89. ggplot(shotDataf, aes(x=LOC_X, y=LOC_Y)) +
  90.     annotation_custom(court, -250, 250, -52, 418) +
  91.     geom_point(aes(colour = EVENT_TYPE, alpha = 0.8), size = 3) +
  92.     scale_color_manual(values = c("#008000", "#FF6347")) +
  93.     guides(alpha = FALSE, size = FALSE) +
  94.     xlim(250, -250) +
  95.     ylim(-52, 418) +
  96.     geom_rug(alpha = 0.2) +
  97.     coord_fixed() +
  98.     ggtitle(paste("Shot Chart\\n", unique(shotDataf$PLAYER_NAME), sep = "")) +
  99.     theme(line = element_blank(),
  100.         axis.title.x = element_blank(),
  101.         axis.title.y = element_blank(),
  102.         axis.text.x = element_blank(),
  103.         axis.text.y = element_blank(),
  104.         legend.title = element_blank(),
  105.         plot.title = element_text(size = 17, lineheight = 1.2, face = "bold"))
  106.  
  107. # add player photo and footnote to the plot
  108. pushViewport(viewport(x = unit(0.9, "npc"), y = unit(0.8, "npc")))
  109.     print(grid.draw(playerImg), newpage=FALSE)
  110.     grid.text(label = "thedatagame.com.au", just = "centre", vjust = 50)
  111.  
  112.  
  113.  
  114. # plot shots using ggplot, hex bins, NBA court backgroung image.
  115. ggplot(shotDataf, aes(x=LOC_X, y=LOC_Y)) +
  116.     annotation_custom(court, -250, 250, -52, 418) +
  117.     stat_binhex(bins = 25, colour = "gray", alpha = 0.7) +
  118.     scale_fill_gradientn(colours = c("yellow","orange","red")) +
  119.     guides(alpha = FALSE, size = FALSE) +
  120.     xlim(250, -250) +
  121.     ylim(-52, 418) +
  122.     geom_rug(alpha = 0.2) +
  123.     coord_fixed() +
  124.     ggtitle(paste("Shot Chart\\n", unique(shotDataf$PLAYER_NAME), sep = "")) +
  125.     theme(line = element_blank(),
  126.         axis.title.x = element_blank(),
  127.         axis.title.y = element_blank(),
  128.         axis.text.x = element_blank(),
  129.         axis.text.y = element_blank(),
  130.         legend.title = element_blank(),
  131.         plot.title = element_text(size = 17, lineheight = 1.2, face = "bold"))
  132.  
  133. # add player photo and footnote to the plot
  134. pushViewport(viewport(x = unit(0.9, "npc"), y = unit(0.8, "npc")))
  135.     print(grid.draw(playerImg), newpage=FALSE)
  136.     grid.text(label = "thedatagame.com.au", just = "centre", vjust = 50)
  137.  
  138.  
  139. ## zone accuracy plot
  140. # exclude backcourt shots
  141. shotDataS <- shotDataf[which(!shotDataf$SHOT_ZONE_BASIC==\'Backcourt\'), ]
  142.  
  143. # summarise shot data
  144. library(plyr)
  145. shotS <- ddply(shotDataS, .(SHOT_ZONE_BASIC), summarize,
  146.         SHOTS_ATTEMPTED = length(SHOT_MADE_FLAG),
  147.         SHOTS_MADE = sum(as.numeric(as.character(SHOT_MADE_FLAG))),
  148.         MLOC_X = mean(LOC_X),
  149.         MLOC_Y = mean(LOC_Y))
  150.  
  151. # calculate shot zone accuracy and add zone accuracy labels
  152. shotS$SHOT_ACCURACY <- (shotS$SHOTS_MADE / shotS$SHOTS_ATTEMPTED)
  153. shotS$SHOT_ACCURACY_LAB <- paste(as.character(round(100 * shotS$SHOT_ACCURACY, 1)), "%", sep="")
  154.  
  155. # plot shot accuracy per zone
  156. ggplot(shotS, aes(x=MLOC_X, y=MLOC_Y)) +
  157.     annotation_custom(court, -250, 250, -52, 418) +
  158.     geom_point(aes(colour = SHOT_ZONE_BASIC, size = SHOT_ACCURACY, alpha = 0.8), size = 8) +
  159.     geom_text(aes(colour = SHOT_ZONE_BASIC, label = SHOT_ACCURACY_LAB), vjust = -1.2, size = 8) +
  160.     guides(alpha = FALSE, size = FALSE) +
  161.     xlim(250, -250) +
  162.     ylim(-52, 418) +
  163.     coord_fixed() +
  164.     ggtitle(paste("Shot Accuracy\\n", unique(shotDataf$PLAYER_NAME), sep = "")) +
  165.     theme(line = element_blank(),
  166.         axis.title.x = element_blank(),
  167.         axis.title.y = element_blank(),
  168.         axis.text.x = element_blank(),
  169.         axis.text.y = element_blank(),
  170.         legend.title = element_blank(),
  171.         legend.text=element_text(size = 12),
  172.         plot.title = element_text(size = 17, lineheight = 1.2, face = "bold"))
  173.  
  174. # add player photo and footnote to the plot
  175. pushViewport(viewport(x = unit(0.9, "npc"), y = unit(0.8, "npc")))
  176.     print(grid.draw(playerImg), newpage=FALSE)
  177.     grid.text(label = "Hasan Diwan <hasandiwan@gmail.com> http://www.prolificprogrammer.com", just = "centre", vjust = 50)
');