code.R
# get data from the usda
funding <- read.csv(
"http://portal.nifa.usda.gov/web/maps/data/nifa_funding_by_district_year_funding_type_district_dollars_v3.csv",
stringsAsFactors = F
)
codes <- read.delim(
"http://portal.nifa.usda.gov/web/maps/data/us-state-names.tsv",
stringsAsFactors = F
)
colnames(codes)[2] <- "STATE_CODE"
#a little regex to make ids strings instead of numbers
#sink("us-congress-113.stringid.json")
#cat(gsub(
# x=readLines("us-congress-113.json"),
# pattern= "(id\":)(\\d+)\\b",
# replacement="\\1\"c\\2\""
#))
#sink()
require(dplyr)
#blend funding and codes into one data source
funding <- left_join(funding,codes)
funding$key <- ifelse(
nchar(funding$STATE_CONGRESSIONAL_DISTRICT)==2,
paste0("c",funding$id,funding$STATE_CONGRESSIONAL_DISTRICT),
paste0("c",funding$id,"0",funding$STATE_CONGRESSIONAL_DISTRICT)
)
funding_total <- funding %.%
dplyr::group_by(AWARD_FISCAL_YEAR,key, STATE_NAME, STATE_CONGRESSIONAL_DISTRICT ) %.%
dplyr::summarise(ALL_FUNDING = sum(FEDERAL_AWARD_DOLLARS))
#in early testing used this to make a json source
#sink("funding.json")
#cat(jsonlite::toJSON(
# funding %.%
# filter( AWARD_FISCAL_YEAR == 2013 )
#))
#sink()
#now let's try rmaps
#require(devtools)
#install_github("rMaps","ramnathv")
require(rMaps)
#need datamaps.none instead of datamaps.us,.world,.all
#https://github.com/ramnathv/rMaps/issues/29
#a hack to accomplish is to override the ref class until fixed
#or just define your own library with config.yml datamaps.none
#ichoropleth has some issues with cuts on this series
ichoropleth2 <- function(x, data, pal = "Blues", ncuts = 5, animate = NULL, play = F, map = 'usa', legend = TRUE, labels = TRUE, ...){
d <- Datamaps$new()
fml = lattice::latticeParseFormula(x, data = data)
data = transform(data,
fillKey = cut(
fml$left,
unique(quantile(fml$left, seq(0, 1, 1/ncuts))),
include.lowest = TRUE,
ordered_result = TRUE
)
)
fillColors = brewer.pal(ncuts, pal)
d$set(
scope = map,
fills = as.list(setNames(fillColors, levels(data$fillKey))),
legend = legend,
labels = labels,
...
)
if (!is.null(animate)){
range_ = summary(data[[animate]])
data = dlply(data, animate, function(x){
y = toJSONArray2(x, json = F)
names(y) = lapply(y, '[[', fml$right.name)
return(y)
})
d$set(
bodyattrs = "ng-app ng-controller='rChartsCtrl'"
)
d$addAssets(
jshead = "http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"
)
if (play == T){
d$setTemplate(chartDiv = sprintf("
<div class='container'>
<button ng-click='animateMap()'>Play</button>
<span ng-bind='year'></span>
<div id='{{chartId}}' class='rChart datamaps'></div>
</div>
<script>
function rChartsCtrl($scope, $timeout){
$scope.year = %s;
$scope.animateMap = function(){
if ($scope.year > %s){
return;
}
map{{chartId}}.updateChoropleth(chartParams.newData[$scope.year]);
$scope.year += 1
$timeout($scope.animateMap, 1000)
}
}
</script>", range_[1], range_[6])
)
} else {
d$setTemplate(chartDiv = sprintf("
<div class='container'>
<input id='slider' type='range' min=%s max=%s ng-model='year' width=200>
<span ng-bind='year'></span>
<div id='{{chartId}}' class='rChart datamaps'></div>
</div>
<script>
function rChartsCtrl($scope){
$scope.year = %s;
$scope.$watch('year', function(newYear){
map{{chartId}}.updateChoropleth(chartParams.newData[newYear]);
})
}
</script>", range_[1], range_[6], range_[1])
)
}
d$set(newData = data, data = data[[1]])
} else {
d$set(data = dlply(data, fml$right.name))
}
return(d)
}
require(rCharts)
require(RColorBrewer)
require(plyr)
mapUSDA <- ichoropleth2(
ALL_FUNDING ~ key,
data = funding_total,
pal = 'PuRd',
ncuts = 5,
#set ncuts to 1 since any > 1 creates multiple 0
#might need to do unique when performing cuts
#unique(quantile(fml$left, seq(0, 1, 1/ncuts)))
animate = 'AWARD_FISCAL_YEAR',
map = "districts"
)
#still get some nas for fills so fix
#use one for 0
#mapUSDA$params$fills[4] <- "#e6e6e6"
#names(mapUSDA$params$fills)[4] <- "0"
#get rid of the 4th and 5th
mapUSDA$params$fills <- mapUSDA$params$fills[1:3]
#don't need two sets of data
#handle in javascript
mapUSDA$params$data <- NULL
mapUSDA$set( geographyConfig = list(
dataUrl = 'us-congress-113.stringid.json',
highlightFillColor = 'orange',
highlightBorderColor = 'white',
highlightBorderWidth = 1
))
mapUSDA$set(popup_template =
"<div class=\"hoverinfo\">
<h3>
{{ data.STATE_NAME }} : {{ data.STATE_CONGRESSIONAL_DISTRICT }}
</h3>
<strong>Total Funding:</strong> {{#data.ALL_FUNDING}}{{ formatPrice this }}{{/data.ALL_FUNDING}}
<div>"
)
mapUSDA$setTemplate(afterScript =
'
<script>
Handlebars.registerHelper("formatPrice", function(d) {
return d3.format("$,.0f")(d);
});
</script>
'
)
mapUSDA$LIB$url = "."
mapUSDA$templates$script = "./chart_usda.html"
#mapUSDA$show(cdn=T)
mapUSDA$save("mapUSDA.html",cdn=T)
datamaps.none.min.js
!function(){function a(a){return this.svg=d3.select(a).append("svg").attr("width",a.offsetWidth).attr("class","datamap").attr("height",a.offsetHeight),this.svg}function b(a,b){var c,d;return b&&"undefined"==typeof b.scope&&(b.scope="world"),"usa"===b.scope?c=d3.geo.albersUsa().scale(a.offsetWidth).translate([a.offsetWidth/2,a.offsetHeight/2]):"world"===b.scope&&(c=d3.geo[b.projection]().scale((a.offsetWidth+1)/2/Math.PI).translate([a.offsetWidth/2,a.offsetHeight/("mercator"===b.projection?1.45:1.8)])),d=d3.geo.path().projection(c),{path:d,projection:c}}function c(){d3.select(".datamaps-style-block").empty()&&d3.select("head").attr("class","datamaps-style-block").append("style").html('.datamap path {stroke: #FFFFFF; stroke-width: 1px;} .datamaps-legend dt, .datamaps-legend dd { float: left; margin: 0 3px 0 0;} .datamaps-legend dd {width: 20px; margin-right: 6px; border-radius: 3px;} .datamaps-legend {padding-bottom: 20px; z-index: 1001; position: absolute; left: 4px; font-size: 12px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;} .datamaps-hoverover {display: none; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; } .hoverinfo {padding: 4px; border-radius: 1px; background-color: #FFF; box-shadow: 1px 1px 5px #CCC; font-size: 12px; border: 1px solid #CCC; } .hoverinfo hr {border:1px dotted #CCC; }')}function d(a){var b=this.options.fills,c=this.options.data||{},d=this.options.geographyConfig,e=this.svg.select("g.datamaps-subunits");e.empty()&&(e=this.addLayer("datamaps-subunits",null,!0));var f=topojson.feature(a,a.objects[this.options.scope]).features;d.hideAntarctica&&(f=f.filter(function(a){return"ATA"!==a.id}));var g=e.selectAll("path.datamaps-subunit").data(f);g.enter().append("path").attr("d",this.path).attr("class",function(a){return"datamaps-subunit "+a.id}).attr("data-info",function(a){return JSON.stringify(c[a.id])}).style("fill",function(a){var d;return c[a.id]&&(d=b[c[a.id].fillKey]),d||b.defaultFill}).style("stroke-width",d.borderWidth).style("stroke",d.borderColor)}function e(){function a(){this.parentNode.appendChild(this)}var b=this.svg,c=this,d=this.options.geographyConfig;(d.highlightOnHover||d.popupOnHover)&&b.selectAll(".datamaps-subunit").on("mouseover",function(e){var f=d3.select(this);if(d.highlightOnHover){var g={fill:f.style("fill"),stroke:f.style("stroke"),"stroke-width":f.style("stroke-width"),"fill-opacity":f.style("fill-opacity")};f.style("fill",d.highlightFillColor).style("stroke",d.highlightBorderColor).style("stroke-width",d.highlightBorderWidth).style("fill-opacity",d.highlightFillOpacity).attr("data-previousAttributes",JSON.stringify(g)),/MSIE/.test(navigator.userAgent)||a.call(this)}d.popupOnHover&&c.updatePopup(f,e,d,b)}).on("mouseout",function(){var a=d3.select(this);if(d.highlightOnHover){var b=JSON.parse(a.attr("data-previousAttributes"));for(var c in b)a.style(c,b[c])}a.on("mousemove",null),d3.selectAll(".datamaps-hoverover").style("display","none")})}function f(a,b){if(b=b||{},this.options.fills){var c="<dl>",d="";b.legendTitle&&(c="<h2>"+b.legendTitle+"</h2>"+c);for(var e in this.options.fills){if("defaultFill"===e){if(!b.defaultFillName)continue;d=b.defaultFillName}else d=b.labels&&b.labels[e]?b.labels[e]:e+": ";c+="<dt>"+d+"</dt>",c+='<dd style="background-color:'+this.options.fills[e]+'"> </dd>'}c+="</dl>",d3.select(this.options.element).append("div").attr("class","datamaps-legend").html(c)}}function g(a,b,c){var d=this;if(this.svg,!b||b&&!b.slice)throw"Datamaps Error - arcs must be an array";"undefined"==typeof c&&(c=l.arcConfig);var e=a.selectAll("path.datamaps-arc").data(b,JSON.stringify);e.enter().append("svg:path").attr("class","datamaps-arc").style("stroke-linecap","round").style("stroke",function(a){return a.options&&a.options.strokeColor?a.options.strokeColor:c.strokeColor}).style("fill","none").style("stroke-width",function(a){return a.options&&a.options.strokeWidth?a.options.strokeWidth:c.strokeWidth}).attr("d",function(a){var b=d.latLngToXY(a.origin.latitude,a.origin.longitude),e=d.latLngToXY(a.destination.latitude,a.destination.longitude),f=[(b[0]+e[0])/2,(b[1]+e[1])/2];return"M"+b[0]+","+b[1]+"S"+(f[0]+50*c.arcSharpness)+","+(f[1]-75*c.arcSharpness)+","+e[0]+","+e[1]}).transition().delay(100).style("fill",function(){var a=this.getTotalLength();return this.style.transition=this.style.WebkitTransition="none",this.style.strokeDasharray=a+" "+a,this.style.strokeDashoffset=a,this.getBoundingClientRect(),this.style.transition=this.style.WebkitTransition="stroke-dashoffset "+c.animationSpeed+"ms ease-out",this.style.strokeDashoffset="0","none"}),e.exit().transition().style("opacity",0).remove()}function h(a,b){var c=this;b=b||{};var d=this.projection([-67.707617,42.722131]);this.svg.selectAll(".datamaps-subunit").attr("data-foo",function(e){var f=c.path.centroid(e),g=7.5,h=5;["FL","KY","MI"].indexOf(e.id)>-1&&(g=-2.5),"NY"===e.id&&(g=-1),"MI"===e.id&&(h=18),"LA"===e.id&&(g=13);var i,j;i=f[0]-g,j=f[1]+h;var k=["VT","NH","MA","RI","CT","NJ","DE","MD","DC"].indexOf(e.id);if(k>-1){var l=d[1];i=d[0],j=l+k*(2+(b.fontSize||12)),a.append("line").attr("x1",i-3).attr("y1",j-5).attr("x2",f[0]).attr("y2",f[1]).style("stroke",b.labelColor||"#000").style("stroke-width",b.lineWidth||1)}return a.append("text").attr("x",i).attr("y",j).style("font-size",(b.fontSize||10)+"px").style("font-family",b.fontFamily||"Verdana").style("fill",b.labelColor||"#000").text(e.id),"bar"})}function i(a,b,c){var d=this,e=this.options.fills,f=this.svg;if(!b||b&&!b.slice)throw"Datamaps Error - bubbles must be an array";var g=a.selectAll("circle.datamaps-bubble").data(b,JSON.stringify);g.enter().append("svg:circle").attr("class","datamaps-bubble").attr("cx",function(a){var b=d.latLngToXY(a.latitude,a.longitude);return b?b[0]:void 0}).attr("cy",function(a){var b=d.latLngToXY(a.latitude,a.longitude);return b?b[1]:void 0}).attr("r",0).attr("data-info",function(a){return JSON.stringify(a)}).style("stroke",c.borderColor).style("stroke-width",c.borderWidth).style("fill-opacity",c.fillOpacity).style("fill",function(a){var b=e[a.fillKey];return b||e.defaultFill}).on("mouseover",function(a){var b=d3.select(this);if(c.highlightOnHover){var e={fill:b.style("fill"),stroke:b.style("stroke"),"stroke-width":b.style("stroke-width"),"fill-opacity":b.style("fill-opacity")};b.style("fill",c.highlightFillColor).style("stroke",c.highlightBorderColor).style("stroke-width",c.highlightBorderWidth).style("fill-opacity",c.highlightFillOpacity).attr("data-previousAttributes",JSON.stringify(e))}c.popupOnHover&&d.updatePopup(b,a,c,f)}).on("mouseout",function(){var a=d3.select(this);if(c.highlightOnHover){var b=JSON.parse(a.attr("data-previousAttributes"));for(var d in b)a.style(d,b[d])}d3.selectAll(".datamaps-hoverover").style("display","none")}).transition().duration(400).attr("r",function(a){return a.radius}),g.exit().transition().delay(c.exitDelay).attr("r",0).remove()}function j(a){return Array.prototype.slice.call(arguments,1).forEach(function(b){if(b)for(var c in b)null==a[c]&&(a[c]=b[c])}),a}function k(b){if("undefined"==typeof d3||"undefined"==typeof topojson)throw new Error("Include d3.js (v3.0.3 or greater) and topojson on this page before creating a new map");return this.options=j(b,l),this.options.geographyConfig=j(b.geographyConfig,l.geographyConfig),this.options.bubblesConfig=j(b.bubblesConfig,l.bubblesConfig),this.options.arcConfig=j(b.arcConfig,l.arcConfig),d3.select(this.options.element).select("svg").length>0&&a.call(this,this.options.element),this.addPlugin("bubbles",i),this.addPlugin("legend",f),this.addPlugin("arc",g),this.addPlugin("labels",h),this.options.disableDefaultStyles||c(),this.draw()}var l={scope:"world",setProjection:b,projection:"equirectangular",done:function(){},fills:{defaultFill:"#ABDDA4"},geographyConfig:{dataUrl:null,hideAntarctica:!0,borderWidth:1,borderColor:"#FDFDFD",popupTemplate:function(a){return'<div class="hoverinfo"><strong>'+a.properties.name+"</strong></div>"},popupOnHover:!0,highlightOnHover:!0,highlightFillColor:"#FC8D59",highlightBorderColor:"rgba(250, 15, 160, 0.2)",highlightBorderWidth:2},bubblesConfig:{borderWidth:2,borderColor:"#FFFFFF",popupOnHover:!0,popupTemplate:function(a,b){return'<div class="hoverinfo"><strong>'+b.name+"</strong></div>"},fillOpacity:.75,animate:!0,highlightOnHover:!0,highlightFillColor:"#FC8D59",highlightBorderColor:"rgba(250, 15, 160, 0.2)",highlightBorderWidth:2,highlightFillOpacity:.85,exitDelay:100},arcConfig:{strokeColor:"#DD1C77",strokeWidth:1,arcSharpness:1,animationSpeed:600}};k.prototype.draw=function(){function a(a){d.call(b,a),e.call(b),(b.options.geographyConfig.popupOnHover||b.options.bubblesConfig.popupOnHover)&&(hoverover=d3.select(b.options.element).append("div").attr("class","datamaps-hoverover").style("z-index",10001).style("position","absolute")),b.options.done(b)}var b=this,c=b.options,f=c.setProjection.apply(b,[c.element,c]);return this.path=f.path,this.projection=f.projection,c.geographyConfig.dataUrl?d3.json(c.geographyConfig.dataUrl,function(c,d){if(c)throw new Error(c);b.customTopo=d,a(d)}):a(this[c.scope+"Topo"]),this},k.prototype.worldTopo="__WORLD__",k.prototype.usaTopo="__USA__",k.prototype.latLngToXY=function(a,b){return this.projection([b,a])},k.prototype.addLayer=function(a,b,c){var d;return d=c?this.svg.insert("g",":first-child"):this.svg.append("g"),d.attr("id",b||"").attr("class",a||"")},k.prototype.updateChoropleth=function(a){var b=this.svg;for(var c in a)if(a.hasOwnProperty(c)){var d,e=a[c];if(!c)continue;d="string"==typeof e?e:"string"==typeof e.color?e.color:this.options.fills[e.fillKey],e===Object(e)&&(this.options.data[c]=j(e,this.options.data[c]||{}),this.svg.select("."+c).attr("data-info",JSON.stringify(this.options.data[c]))),b.selectAll("."+c).transition().style("fill",d)}},k.prototype.updatePopup=function(a,b,c){var d=this;a.on("mousemove",null),a.on("mousemove",function(){var e=d3.mouse(this);d3.select(d.svg[0][0].parentNode).select(".datamaps-hoverover").style("top",e[1]+30+"px").html(function(){var d=JSON.parse(a.attr("data-info"));return c.popupTemplate(b,d)}).style("left",e[0]+"px")}),d3.select(d.svg[0][0].parentNode).select(".datamaps-hoverover").style("display","block")},k.prototype.addPlugin=function(a,b){"undefined"==typeof k.prototype[a]&&(k.prototype[a]=function(c,d,e,f){var g;"undefined"==typeof f&&(f=!1),"function"==typeof d&&(e=d,d=void 0),d=j(d||{},l[a+"Config"]),!f&&this.options[a+"Layer"]?(g=this.options[a+"Layer"],d=d||this.options[a+"Options"]):(g=this.addLayer(a),this.options[a+"Layer"]=g,this.options[a+"Options"]=d),b.apply(this,[g,c,d]),e&&e(g)})},"function"==typeof define&&define.amd?define("datamaps",[],function(){return k}):window.Datamap=window.Datamaps=k,window.jQuery&&(window.jQuery.fn.datamaps=function(a,b){a=a||{},a.element=this[0];var c=new k(a);return"function"==typeof b&&b(c,a),this})}();