Skip to content

Instantly share code, notes, and snippets.

@expersso
Created May 20, 2016 14:20
Show Gist options
  • Save expersso/276cd2466d486c3a094431520ea5f727 to your computer and use it in GitHub Desktop.
Save expersso/276cd2466d486c3a094431520ea5f727 to your computer and use it in GitHub Desktop.
Explorations in functional programming
library(httr)
library(purrr)
library(dplyr)
library(ggplot2)
library(scales)
library(ggthemes)
with_msg <- function(msg, f) {
function(...) {
args <- list(...)
message(msg, args[[1]])
f(...)
}
}
get_data <- function(city) {
url <- paste0("http://api.rentswatch.com/api/cities/", city)
response <- GET(url)
stop_for_status(response)
data <- content(response)
data$months %>%
map_df(as_data_frame) %>%
mutate(month = as.Date(paste0(month, "-01")),
city = city) %>%
rename("date" = month)
}
retrieve_data <- with_msg("Retrieving: ", safely(get_data))
cities <- c("Berlin", "Rome", "Madrid", "Milano", "Munich", "Brussels")
df <- cities %>% map(retrieve_data) %>% map_df("result")
# Retrieving: Berlin
# Retrieving: Rome
# Retrieving: Madrid
# Retrieving: Milano
# Retrieving: Munich
# Retrieving: Brussels
head(df)
# Source: local data frame [6 x 6]
# date total avgPricePerSqm lastSnapshot stdErr city
# (date) (int) (dbl) (int) (dbl) (chr)
# 1 2015-08-01 2037 12.20869 1463557537 0.08568070 Berlin
# 2 2015-09-01 1712 12.33864 1463557537 0.09864115 Berlin
# 3 2015-10-01 2320 11.77665 1463557537 0.08046912 Berlin
# 4 2015-11-01 3897 11.90312 1463557537 0.06291511 Berlin
# 5 2015-12-01 3424 12.16882 1463557537 0.07454032 Berlin
# 6 2016-01-01 2394 11.98097 1463557537 0.08729184 Berlin
ggplot(df, aes(x = date, y = avgPricePerSqm, group = city)) +
geom_ribbon(aes(
ymin = avgPricePerSqm - 2 * stdErr,
ymax = avgPricePerSqm + 2 * stdErr,
fill = city
),
alpha = 0.2) +
geom_line(aes(color = city)) +
geom_text(
aes(label = sprintf(" %s", city), color = city),
data = filter(df, date == max(date)),
size = 3,
fontface = "bold",
hjust = 0
) +
scale_color_few() +
scale_fill_few() +
scale_y_continuous(breaks = pretty_breaks(10)) +
scale_x_date(
breaks = date_breaks("2 months"),
labels = date_format("%b %Y", "CET"),
expand = c(0, 0),
limits = c(min(df$date), max(df$date) + 40)
) +
theme_light() +
theme(
legend.position = "none",
plot.caption = element_text(color = "grey50", size = rel(0.5)),
plot.subtitle = element_text(color = "grey50"),
plot.title = element_text(color = "grey30"),
axis.text = element_text(size = rel(0.7))
) +
labs(
x = NULL,
y = NULL,
title = "Rents in major European citites",
subtitle = "Average price per square meter (in Euros)",
caption = "\nSource: Rentswatch.com"
)
@expersso
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment