Skip to content

Instantly share code, notes, and snippets.

@andresAlvarado
Last active April 3, 2017 01:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save andresAlvarado/938ffb57e929acf17a3b033c456e5912 to your computer and use it in GitHub Desktop.
Save andresAlvarado/938ffb57e929acf17a3b033c456e5912 to your computer and use it in GitHub Desktop.
library( package = 'dplyr' )
library( package = 'ggplot2' )
library( package = 'data.table' )
# Column types
l_g_cols <- c( 'NULL'
, 'character' # GAME_DT
, rep( x = 'NULL', times = 5 )
, 'character' # AWAY_TEAM_ID
, 'character' # HOME_TEAM_ID
, rep( x = 'NULL', times = 25)
, 'numeric' # AWAY_SCORE_CT
, 'numeric' # HOME_SCORE_CT
, rep( x = 'NULL', times = 143)
)
# Column names
l_g_names <- c( 'GAME_DATE','AWAY_TEAM','HOME_TEAM','AWAY_SCORE','HOME_SCORE' )
# Read the 2002 season file.
d_games <- fread( input = '2002.csv'
, header = T
, colClasses = l_g_cols
, col.names = l_g_names
)
# Come with a data.frame
# Convert GAME_DATE to a Date variable
# Get the outcome of each game: Did the Athletics win or lose?
# Get the run difference. If Athletics won dif > 0, else dif < 0.
d_games <- filter( .data = d_games, HOME_TEAM == 'OAK' | AWAY_TEAM == 'OAK' ) %>%
mutate( GAME_DATE = as.Date( x = GAME_DATE, format = '%Y%m%d' )
, OUTCOME = ifelse( test = ( HOME_TEAM == 'OAK' & HOME_SCORE > AWAY_SCORE )
| ( AWAY_TEAM == 'OAK' & AWAY_SCORE > HOME_SCORE )
, yes = 'WIN'
, no = 'LOSE'
)
, SCORE_DIFF = ifelse( test = OUTCOME == 'WIN'
, yes = abs( x = HOME_SCORE - AWAY_SCORE )
, no = - abs( x = HOME_SCORE - AWAY_SCORE )
)
)
# Create plot
# Fill of the bars depend on the outcome of the game. Won = Green, Lose = Red
# Y = Difference between the team scores.
g_plot <- ( ggplot( data = d_games
, aes( x = GAME_DATE
, y = SCORE_DIFF
, fill = OUTCOME
, color = OUTCOME
)
)
+ geom_bar( stat = 'identity'
, width = 0.7
, alpha = 0.5
)
+ theme( axis.ticks = element_blank()
, axis.text = element_blank()
, title = element_blank()
, panel.background = element_blank()
, legend.position = 'none'
)
+ scale_fill_manual( values = c('red2','green4') )
+ scale_color_manual( values = c('red2','green4') )
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment