Image

Visualizing Calls for Service Data

At work I have been working with some EMS calls for service data. After geocoding the data, I put together the following animation in R showing the calls for service by month:
animationDue to confidentiality reasons I cannot disclose the data, however this is the code that created this animation:

library(ggplot2)
library(ggmap)
library(animation)
# Pull in the data
df <- read.csv("Greene Complete.csv", stringsAsFactors=F)
# Change the types
df$X <- as.numeric(df$X)
df$Y <- as.numeric(df$Y)
# Subset the data
df <- df[c('Month','X','Y')]
# Remove NA's
df <- df[!is.na(df$X),]
# Build the month vector
months <- df$Month
months <- months[!duplicated(months)]

saveGIF({
  for(month in months){
    data <- df[df$Month == month,]
    # Build the map
    map <- get_map(location = c(lon = -74.123996, lat = 42.295732), color = 'bw', maptype = "roadmap", zoom = 10)
    map <- ggmap(map, extent = "device", ylab = "Latitude", xlab = "Longitude")
    #map <- map + geom_point(data=data, aes(x=X, y=Y), size=2, color='red')
  
    overlay <- stat_density2d(data = data, 
                              aes(x = X, y = Y, fill = ..level.. , alpha = ..level..), 
                              size = 2, bins = 10, geom = "polygon")
    map <- map + overlay
    map <- map + scale_fill_gradient("Calls For\nService")
    map <- map + scale_alpha(range = c(0.4, 0.75), guide = FALSE)
    map <- map + guides(fill = guide_colorbar(barwidth = 1.5, barheight = 10))
    print(map)
  }
})

I would like to fix the scale to make it consistent month to month.

Pulling in BEA API Data Into R

I have begun writing a script that I would like to pass on.  It pulls in GDP by MSA data using the BEA’s API into R.  This is the beginning of an analysis I am hoping to preform.  Hopefully others find this helpful.

# Load the needed libraries
library(RCurl)
library(rjson)
library(reshape2)

# Set my BEA API key
bea.api.key <- “XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX”
bea.api.url <- “http://www.bea.gov/api/data&#8221;

# Read in the FIPS codes for the MSA’s
msa = read.csv(“bea_msa_fips.csv”,head=TRUE,sep=”,”)
fips = msa$FIPS

# Create data frame to hold the API results
df <- data.frame()

# Loop through the MSA’s to request the MSA GDP
for (i in 1:length(fips))
{
# Make the request to the API
req <- paste(“http://www.bea.gov/api/data/?&UserID=&#8221;, bea.api.key, “&method=GetData&datasetname=RegionalData&KeyCode=GDP_MP&GeoFIPS=”, fips[i], “&ResultFormat=json”, sep=””)

# Parse the JSON response
res <- fromJSON(getURL(req))

# Since there are multiple years in the response we need to loop through them
for (j in 1:length(res$BEAAPI$Results$Data))
{
# Append the API result to the data frame
r <- as.data.frame(res$BEAAPI$Results$Data[j])
df <- rbind(df,r)
}
}


msa.gdp <- dcast(df, GeoName + GeoFips ~ TimePeriod, value.var="DataValue")

If you are interested in using this you will need this csv.