Skip to content

Instantly share code, notes, and snippets.

@mkiang mkiang/mtafares.R
Last active Aug 29, 2015

Embed
What would you like to do?
MetroCard Graph
## 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
You can’t perform that action at this time.