Skip to content

Instantly share code, notes, and snippets.

@markmarkoh
Forked from timelyportfolio/chart_usda.html
Last active August 29, 2015 13:57

Revisions

  1. markmarkoh revised this gist Mar 28, 2014. 2 changed files with 4 additions and 2 deletions.
    4 changes: 3 additions & 1 deletion index.html
    Original file line number Diff line number Diff line change
    @@ -4,6 +4,8 @@
    <script src="http://d3js.org/d3.v3.min.js"></script>
    <script src="http://d3js.org/topojson.v1.min.js"></script>
    <script src="http://rawgithub.com/markmarkoh/datamaps/master/dist/datamaps.none.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/1.4.5/numeral.min.js"></script>


    <body>
    <div id="container" style="position: relative; width: 500px; height: 300px;"></div>
    @@ -19,7 +21,7 @@
    highlightBorderWidth: 1,
    popupTemplate: function(geo, data) {
    return ['<div class="hoverinfo"><strong>',
    data.map(function(d){return d3.values(d)}).join('<br>'),
    data.map(function(d){return numeral(d3.values(d)).format('0,0')}).join('<br>'),
    '</strong></div>'].join('');
    }
    },
    2 changes: 1 addition & 1 deletion us-congress-113.stringid.json
    1 addition, 1 deletion not shown because the diff is too large. Please use a local Git client to view these changes.
  2. @timelyportfolio timelyportfolio revised this gist Mar 28, 2014. 3 changed files with 7972 additions and 12 deletions.
    3 changes: 2 additions & 1 deletion chart_usda.html
    Original file line number Diff line number Diff line change
    @@ -7,7 +7,8 @@

    {{# popup_template }}
    var tmplFn = Handlebars.compile(
    document.getElementById("popup-template").innerHTML
    document.getElementById("popup-template").innerHTML.replace(/\"#!(.*?)!#\"/g, "\\$1")
    //document.getElementById("popup-template").innerHTML
    );
    var popupFn = function(geography, data) {
    return tmplFn({geography: geography, data: data});
    21 changes: 10 additions & 11 deletions code.R
    Original file line number Diff line number Diff line change
    @@ -28,8 +28,8 @@ funding$key <- ifelse(
    )

    funding_total <- funding %.%
    group_by(AWARD_FISCAL_YEAR, key) %.%
    summarise(ALL_FUNDING = sum(FEDERAL_AWARD_DOLLARS))
    dplyr::group_by(AWARD_FISCAL_YEAR,key) %.%
    dplyr::summarise(ALL_FUNDING = sum(FEDERAL_AWARD_DOLLARS))

    #in early testing used this to make a json source
    #sink("funding.json")
    @@ -150,10 +150,10 @@ mapUSDA <- ichoropleth2(
    )
    #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 5th
    mapUSDA$params$fills <- mapUSDA$params$fills[1:4]
    #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
    @@ -164,12 +164,11 @@ mapUSDA$set( geographyConfig = list(
    dataUrl = 'us-congress-113.stringid.json',
    highlightFillColor = 'orange',
    highlightBorderColor = 'white',
    highlightBorderWidth = 1#,
    #popupTemplate = function(geo, data) {
    # return ['<div class="hoverinfo"><strong>',
    # data.map(function(d){return d3.values(d)}).join('<br>'),
    # '</strong></div>'].join('');
    highlightBorderWidth = 1
    ))

    mapUSDA$set(popup_template = "<div class=\"hoverinfo\"><strong>{{ data.ALL_FUNDING }}</strong><div>")

    mapUSDA$LIB$url = "."
    mapUSDA$templates$script = "./chart_usda.html"
    #mapUSDA$show(cdn=T)
    7,960 changes: 7,960 additions & 0 deletions mapUSDA.html
    7,960 additions, 0 deletions not shown because the diff is too large. Please use a local Git client to view these changes.
  3. @timelyportfolio timelyportfolio revised this gist Mar 28, 2014. 4 changed files with 231 additions and 8 deletions.
    61 changes: 61 additions & 0 deletions chart_usda.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,61 @@
    <script id='popup-template' type='text/x-handlebars-template'>
    {{{ popup_template }}}
    </script>
    <script>
    var chartParams = {{{ chartParams }}}
    chartParams.element = document.getElementById('{{chartId}}')

    {{# popup_template }}
    var tmplFn = Handlebars.compile(
    document.getElementById("popup-template").innerHTML
    );
    var popupFn = function(geography, data) {
    return tmplFn({geography: geography, data: data});
    }
    if (chartParams.geographyConfig){
    chartParams.geographyConfig.popupTemplate = popupFn
    } else {
    chartParams.geographyConfig = {"popupTemplate": popupFn}
    }
    {{/ popup_template }}

    chartParams.setProjection = function( element, options ) {
    var projection, path;

    projection = d3.geo.albersUsa()
    .scale(element.offsetWidth)
    .translate([element.offsetWidth / 2, element.offsetHeight / 2]);

    path = d3.geo.path()
    .projection( projection );

    return {path: path, projection: projection};
    }

    chartParams.data = chartParams.newData[d3.keys(chartParams.newData)[0]];

    var map{{chartId}} = new Datamap(chartParams);



    // draw a bubble map if specified
    if (chartParams.bubbles) {
    var bubbles = chartParams.bubbles
    map{{chartId}}.bubbles(bubbles)
    }

    if (chartParams.labels){
    map{{chartId}}.labels()
    }

    if (chartParams.legend){
    map{{chartId}}.legend()
    }

    </script>

    <style>
    .datamaps {
    position: relative;
    }
    </style>
    169 changes: 161 additions & 8 deletions code.R
    Original file line number Diff line number Diff line change
    @@ -9,18 +9,171 @@ codes <- read.delim(
    )
    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 into one data source
    #blend funding and codes into one data source
    funding <- left_join(funding,codes)
    funding$key <- ifelse(
    nchar(funding$STATE_CONGRESSIONAL_DISTRICT)==2,
    paste0(funding$id,funding$STATE_CONGRESSIONAL_DISTRICT),
    paste0(funding$id,"0",funding$STATE_CONGRESSIONAL_DISTRICT)
    paste0("c",funding$id,funding$STATE_CONGRESSIONAL_DISTRICT),
    paste0("c",funding$id,"0",funding$STATE_CONGRESSIONAL_DISTRICT)
    )

    funding_total <- funding %.%
    group_by(AWARD_FISCAL_YEAR, key) %.%
    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(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 5th
    mapUSDA$params$fills <- mapUSDA$params$fills[1:4]

    #don't need two sets of data
    #handle in javascript
    mapUSDA$params$data <- NULL

    sink("funding.json")
    cat(jsonlite::toJSON(
    funding %.%
    filter( AWARD_FISCAL_YEAR == 2013 )

    mapUSDA$set( geographyConfig = list(
    dataUrl = 'us-congress-113.stringid.json',
    highlightFillColor = 'orange',
    highlightBorderColor = 'white',
    highlightBorderWidth = 1#,
    #popupTemplate = function(geo, data) {
    # return ['<div class="hoverinfo"><strong>',
    # data.map(function(d){return d3.values(d)}).join('<br>'),
    # '</strong></div>'].join('');
    ))
    sink()
    mapUSDA$LIB$url = "."
    mapUSDA$templates$script = "./chart_usda.html"
    #mapUSDA$show(cdn=T)

    mapUSDA$save("mapUSDA.html",cdn=T)


    8 changes: 8 additions & 0 deletions config.yml
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,8 @@
    datamaps:
    jshead: [d3.v3.min.js, topojson.v1.min.js, datamaps.none.min.js]
    cdn:
    jshead:
    - "http://d3js.org/d3.v3.min.js"
    - "http://d3js.org/topojson.v1.min.js"
    - "http://datamaps.github.io/scripts/datamaps.none.min.js"
    - "http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0/handlebars.min.js"
    1 change: 1 addition & 0 deletions us-congress-113.stringid.json
    1 addition, 0 deletions not shown because the diff is too large. Please use a local Git client to view these changes.
  4. @timelyportfolio timelyportfolio revised this gist Mar 27, 2014. 5 changed files with 72 additions and 15 deletions.
    26 changes: 26 additions & 0 deletions code.R
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    # 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"

    require(dplyr)
    #blend into one data source
    funding <- left_join(funding,codes)
    funding$key <- ifelse(
    nchar(funding$STATE_CONGRESSIONAL_DISTRICT)==2,
    paste0(funding$id,funding$STATE_CONGRESSIONAL_DISTRICT),
    paste0(funding$id,"0",funding$STATE_CONGRESSIONAL_DISTRICT)
    )

    sink("funding.json")
    cat(jsonlite::toJSON(
    funding %.%
    filter( AWARD_FISCAL_YEAR == 2013 )
    ))
    sink()
    1 change: 1 addition & 0 deletions funding.json
    1 addition, 0 deletions not shown because the diff is too large. Please use a local Git client to view these changes.
    46 changes: 32 additions & 14 deletions index.html
    Original file line number Diff line number Diff line change
    @@ -9,22 +9,40 @@
    <div id="container" style="position: relative; width: 500px; height: 300px;"></div>

    <script>
    d3.json('funding.json', function(err,data){
    var map = new Datamap({
    element: document.getElementById('container'),
    geographyConfig: {
    dataUrl: 'us-congress-113.json'
    },
    scope: 'districts',
    setProjection: function(element) {
    var projection, path;
    projection = d3.geo.albersUsa()
    .scale(element.offsetWidth)
    .translate([element.offsetWidth / 2, element.offsetHeight / 2]);
    path = d3.geo.path()
    .projection( projection );

    return {path: path, projection: projection};
    element: document.getElementById('container'),
    geographyConfig: {
    dataUrl: 'us-congress-113.json',
    highlightFillColor: 'orange',
    highlightBorderColor: 'white',
    highlightBorderWidth: 1,
    popupTemplate: function(geo, data) {
    return ['<div class="hoverinfo"><strong>',
    data.map(function(d){return d3.values(d)}).join('<br>'),
    '</strong></div>'].join('');
    }
    },
    fills: {
    defaultFill: '#e6e6e6',
    someKey: '#fa0fa0'
    },
    data: //{
    //'103': {fillKey: 'someKey'}
    d3.nest().key(function(d){return String(d.key)}).map(data),
    //},
    scope: 'districts',
    setProjection: function(element) {
    var projection, path;
    projection = d3.geo.albersUsa()
    .scale(element.offsetWidth)
    .translate([element.offsetWidth / 2, element.offsetHeight / 2]);
    path = d3.geo.path()
    .projection( projection );

    return {path: path, projection: projection};
    }
    });
    })
    </script>
    </body>
    13 changes: 13 additions & 0 deletions notes.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    http://datamaps.markmarkoh.com/using-custom-map-data-w-datamaps/



    ### not necessary

    install topojson in node
    problems
    - needed to install Visual Studio Express 10
    - needed to use switch in npm install python=python2.7

    topojson
    - topojson --id-property id -o us-congress-113.topo.json us-congress-113.json
    1 change: 0 additions & 1 deletion us-congress-113.topo.json
    0 additions, 1 deletion not shown because the diff is too large. Please use a local Git client to view these changes.
  5. @timelyportfolio timelyportfolio revised this gist Mar 27, 2014. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion index.html
    Original file line number Diff line number Diff line change
    @@ -12,7 +12,7 @@
    var map = new Datamap({
    element: document.getElementById('container'),
    geographyConfig: {
    dataUrl: 'us-congress-113.topo.json'
    dataUrl: 'us-congress-113.json'
    },
    scope: 'districts',
    setProjection: function(element) {
  6. @timelyportfolio timelyportfolio revised this gist Mar 27, 2014. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion index.html
    Original file line number Diff line number Diff line change
    @@ -14,7 +14,7 @@
    geographyConfig: {
    dataUrl: 'us-congress-113.topo.json'
    },
    scope: 'custom',
    scope: 'districts',
    setProjection: function(element) {
    var projection, path;
    projection = d3.geo.albersUsa()
  7. @timelyportfolio timelyportfolio revised this gist Mar 27, 2014. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion index.html
    Original file line number Diff line number Diff line change
    @@ -12,7 +12,7 @@
    var map = new Datamap({
    element: document.getElementById('container'),
    geographyConfig: {
    dataUrl: 'us-congress-113.json'
    dataUrl: 'us-congress-113.topo.json'
    },
    scope: 'custom',
    setProjection: function(element) {
  8. @timelyportfolio timelyportfolio revised this gist Mar 27, 2014. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions us-congress-113.topo.json
    1 addition, 0 deletions not shown because the diff is too large. Please use a local Git client to view these changes.
  9. @timelyportfolio timelyportfolio revised this gist Mar 27, 2014. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion index.html
    Original file line number Diff line number Diff line change
    @@ -15,7 +15,7 @@
    dataUrl: 'us-congress-113.json'
    },
    scope: 'custom',
    setProjection: function(element, options) {
    setProjection: function(element) {
    var projection, path;
    projection = d3.geo.albersUsa()
    .scale(element.offsetWidth)
  10. @timelyportfolio timelyportfolio revised this gist Mar 27, 2014. 1 changed file with 7 additions and 2 deletions.
    9 changes: 7 additions & 2 deletions index.html
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,11 @@
    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
    <!DOCTYPE html>
    <meta charset="utf-8">

    <script src="http://d3js.org/d3.v3.min.js"></script>
    <script src="http://d3js.org/topojson.v1.min.js"></script>
    <script src="http://rawgithub.com/markmarkoh/datamaps/master/dist/datamaps.none.min.js"></script>

    <body>
    <div id="container" style="position: relative; width: 500px; height: 300px;"></div>

    <script>
    @@ -22,4 +26,5 @@
    return {path: path, projection: projection};
    }
    });
    </script>
    </script>
    </body>
  11. @timelyportfolio timelyportfolio revised this gist Mar 27, 2014. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions index.html
    Original file line number Diff line number Diff line change
    @@ -1,14 +1,14 @@
    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
    <script src="http://d3js.org/topojson.v1.min.js"></script>
    <script src="./datamaps.none.min.js"></script>
    <script src="http://rawgithub.com/markmarkoh/datamaps/master/dist/datamaps.none.min.js"></script>

    <div id="container" style="position: relative; width: 500px; height: 300px;"></div>

    <script>
    var map = new Datamap({
    element: document.getElementById('container'),
    geographyConfig: {
    dataUrl: './us-congress-113.json'
    dataUrl: 'us-congress-113.json'
    },
    scope: 'custom',
    setProjection: function(element, options) {
  12. @timelyportfolio timelyportfolio revised this gist Mar 27, 2014. 1 changed file with 4 additions and 4 deletions.
    8 changes: 4 additions & 4 deletions index.html
    Original file line number Diff line number Diff line change
    @@ -16,10 +16,10 @@
    projection = d3.geo.albersUsa()
    .scale(element.offsetWidth)
    .translate([element.offsetWidth / 2, element.offsetHeight / 2]);
    }
    path = d3.geo.path()
    .projection( projection );
    path = d3.geo.path()
    .projection( projection );

    return {path: path, projection: projection};
    return {path: path, projection: projection};
    }
    });
    </script>
  13. @timelyportfolio timelyportfolio revised this gist Mar 27, 2014. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions index.html
    Original file line number Diff line number Diff line change
    @@ -1,14 +1,14 @@
    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
    <script src="http://d3js.org/topojson.v1.min.js"></script>
    <script src="/datamaps.none.min.js"></script>
    <script src="./datamaps.none.min.js"></script>

    <div id="container" style="position: relative; width: 500px; height: 300px;"></div>

    <script>
    var map = new Datamap({
    element: document.getElementById('container'),
    geographyConfig: {
    dataUrl: '/us-congress-113.json'
    dataUrl: './us-congress-113.json'
    },
    scope: 'custom',
    setProjection: function(element, options) {
  14. @timelyportfolio timelyportfolio revised this gist Mar 27, 2014. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions index.html
    Original file line number Diff line number Diff line change
    @@ -1,14 +1,14 @@
    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
    <script src="http://d3js.org/topojson.v1.min.js"></script>
    <script src="datamaps.none.min.js"></script>
    <script src="/datamaps.none.min.js"></script>

    <div id="container" style="position: relative; width: 500px; height: 300px;"></div>

    <script>
    var map = new Datamap({
    element: document.getElementById('container'),
    geographyConfig: {
    dataUrl: 'us-congress-113.json'
    dataUrl: '/us-congress-113.json'
    },
    scope: 'custom',
    setProjection: function(element, options) {
  15. @timelyportfolio timelyportfolio revised this gist Mar 27, 2014. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions index.html
    Original file line number Diff line number Diff line change
    @@ -1,14 +1,14 @@
    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
    <script src="http://d3js.org/topojson.v1.min.js"></script>
    <script src="./datamaps.none.min.js"></script>
    <script src="datamaps.none.min.js"></script>

    <div id="container" style="position: relative; width: 500px; height: 300px;"></div>

    <script>
    var map = new Datamap({
    element: document.getElementById('container'),
    geographyConfig: {
    dataUrl: '/us-congress-113.json'
    dataUrl: 'us-congress-113.json'
    },
    scope: 'custom',
    setProjection: function(element, options) {
  16. @timelyportfolio timelyportfolio revised this gist Mar 27, 2014. 1 changed file with 4 additions and 5 deletions.
    9 changes: 4 additions & 5 deletions index.html
    Original file line number Diff line number Diff line change
    @@ -16,11 +16,10 @@
    projection = d3.geo.albersUsa()
    .scale(element.offsetWidth)
    .translate([element.offsetWidth / 2, element.offsetHeight / 2]);
    }
    path = d3.geo.path()
    .projection( projection );

    return {path: path, projection: projection};
    }
    path = d3.geo.path()
    .projection( projection );

    return {path: path, projection: projection};
    });
    </script>
  17. @timelyportfolio timelyportfolio revised this gist Mar 27, 2014. 1 changed file with 3 additions and 1 deletion.
    4 changes: 3 additions & 1 deletion index.html
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,9 @@
    <script src="http://d3js.org/d3.v3.min.js"></script>
    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
    <script src="http://d3js.org/topojson.v1.min.js"></script>
    <script src="./datamaps.none.min.js"></script>

    <div id="container" style="position: relative; width: 500px; height: 300px;"></div>

    <script>
    var map = new Datamap({
    element: document.getElementById('container'),
  18. @timelyportfolio timelyportfolio revised this gist Mar 27, 2014. 1 changed file with 22 additions and 1 deletion.
    23 changes: 22 additions & 1 deletion index.html
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,24 @@
    <script src="http://d3js.org/d3.v3.min.js"></script>
    <script src="http://d3js.org/topojson.v1.min.js"></script>
    <script src="./datamaps.world.min.js"></script>
    <script src="./datamaps.none.min.js"></script>

    <script>
    var map = new Datamap({
    element: document.getElementById('container'),
    geographyConfig: {
    dataUrl: '/us-congress-113.json'
    },
    scope: 'custom',
    setProjection: function(element, options) {
    var projection, path;
    projection = d3.geo.albersUsa()
    .scale(element.offsetWidth)
    .translate([element.offsetWidth / 2, element.offsetHeight / 2]);
    }
    path = d3.geo.path()
    .projection( projection );

    return {path: path, projection: projection};
    }
    });
    </script>
  19. @timelyportfolio timelyportfolio revised this gist Mar 27, 2014. 2 changed files with 4 additions and 0 deletions.
    1 change: 1 addition & 0 deletions datamaps.none.min.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    !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]+'">&nbsp;</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})}();
    3 changes: 3 additions & 0 deletions index.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,3 @@
    <script src="http://d3js.org/d3.v3.min.js"></script>
    <script src="http://d3js.org/topojson.v1.min.js"></script>
    <script src="./datamaps.world.min.js"></script>
  20. @timelyportfolio timelyportfolio created this gist Mar 27, 2014.
    1 change: 1 addition & 0 deletions us-congress-113.json
    1 addition, 0 deletions not shown because the diff is too large. Please use a local Git client to view these changes.