Last active
August 29, 2015 14:17
-
-
Save mkiang/94bd7b167b26c59524bc to your computer and use it in GitHub Desktop.
MetroCard Graph
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Side project name: Refilling MTA cards (March 2015 rates) | |
## Author: Mathew Kiang | |
## See: http://mathewkiang.com/2015/03/23/new-metrocard-rates-and-the-dreaded-dead-zone-of-change/ | |
library(ggplot2) | |
## Define parameters | |
price <- 2.75 | |
bonus <- 1.11 | |
lim <- 0.15 # amount of change willing to tolerate | |
upp <- 25 # upper limit to amount deposited | |
intvl <- 0.05 # intervals the MTA machines allow you to deposit | |
## Define how much you spend and what it's worth | |
spend <- seq(5, upp, by = intvl) | |
worth <- round(spend * bonus, 3) | |
rides <- floor(worth / price) | |
## Calculate change | |
left <- worth %% price | |
## Initialize and fill dataframe | |
mtadf <- data.frame(spend, worth, rides, left) | |
## Make a printable variable $$ variable | |
dolladolla <- paste0('$', sprintf(mtadf$spend[mtadf$left < lim], | |
fmt = '%.02f'), ' ($', | |
sprintf(mtadf$left[mtadf$left < lim], fmt = '%.02f'), ')') | |
mtadf$exact[mtadf$left < lim] <- dolladolla | |
## Take minimum for each ride only -- this only matters if lim > intvl. | |
mins <- aggregate(mtadf$spend, by = list(mtadf$rides), FUN = min)$x | |
mtadf$exact[!(mtadf$spend %in% mins)] <- NA | |
## Plot | |
p <- ggplot(data = mtadf, | |
aes(x = spend, y = rides, color = left)) + | |
geom_point() + | |
theme_classic() + | |
geom_text(aes(label = exact, x = spend - .05, y = rides + .2), | |
vjust = 0, hjust = 0) + | |
theme(legend.position = c(1, 0), | |
legend.justification = c(1, 0)) + | |
scale_color_gradient(name = 'Remaining balance\n(aka "dead zone")', | |
limits = c(0, 3), | |
labels = c("$0", "$1", "$2", "$3"), | |
breaks = 0:3) + | |
scale_y_discrete(breaks = seq(0, 11, by = 2)) + | |
scale_x_continuous(breaks = seq(0, 30, by = 5), | |
limit = c(4.9, 27.5), | |
expand = c(.01, 0)) + | |
labs(x = "Amount Added to Card ($)", | |
y = "# of Rides", | |
title = "Optimal MetroCard Refilling by Number of Rides") | |
ggsave(p, file = './mtafares.jpg', width = 5, height = 2, scale = 2.4) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment