Skip to content

Let's add a map by E2D3

Sawa edited this page Mar 21, 2015 · 4 revisions

Let's add a map by E2D3

Map

add a directory at root https://github.com/e2d3/e2d3-contrib

add a directory for a new chart. E2D3 requires 1 directory for 1 chart.

$ mkdir sample
$ cd sample

add files

main.js in chart's directories must be called to show charts. if you need libraries, you can add the files here like "topojson.js". "README.md" and "thumbnail.png" are shown at the index page users to choose charts.

├── README.md
├── data.tsv
├── ir.topojson
├── main.js
├── thumbnail.png
└── topojson.js

here, I'll show you how to add a choropleth map of Iran by topojson and tsv. this is a topojson file of Iran admin1 (each provinces).

main.js

//# require=d3,topojson

var width = root.clientWidth;
var height = root.clientHeight;

var svg = d3.select(root).append('svg')
  .attr('width', width)
  .attr('height', height)
  .attr('style', 'display: block; margin: auto;');
var projection = d3.geo.mercator()
  .center([53, 35])
  .scale(1200)
  .translate([width / 2, height / 2]);
var path = d3.geo.path()
  .projection(projection);

svg.append('g')
  .attr('id', 'legend_group');

d3.json(baseUrl + '/ir.topojson', function (error, json) {
  svg.selectAll('.states')
    .data(topojson.feature(json, json.objects.ir).features)
  .enter().append('path')
    .attr('stroke', 'gray')
    .attr('stroke-width', '0.5')
    .attr('id', function (d) { return 'state_' + d.properties.adm1_code})
    .attr('class', 'states')
    .attr('fill', '#ffffff')
    .attr('d', path)
    .attr('data-text', function(d){return d.name})
    ;

  reload();
});

function update(data) {
  var map = data.toMap();
  var initIndex = 2;
  var initLabel = map.header[initIndex];
  var values = map.values();

  var tsv = data.toList();
  tsv.forEach(function(d){
    d.Population = +d.Population;
  });
  var color = d3.scale.linear()
    .domain(d3.extent(tsv, function(d){return d.Population}))
    .range(['#ffffff', '#ff0000'])
    .interpolate(d3.interpolateLab);

  svg.selectAll('.states')
    .attr('fill', function (d) {
      var obj = tsv.filter(function(e){return e.Province==d.properties.name})[0];
      if (obj) {
        return color(obj.Population);
      } else {
        return '#cccccc';
      }
    });
}

data.tsv

Province original	Province	Capital	Area	Population	Density (population/km²)	Shahrestans (counties)	Notes	Map
Alborz	Alborz	Karaj	5,833 km2 (2,252 sq mi)	2412513	413.6 inhabitants per square kilometre (1,071/sq mi)	4	Until 23 June 2010, Alborz was part of Tehran province.	IranAlborz.png
Ardabil	Ardebil	Ardabil	17,800 km2 (6,900 sq mi)	1248488	70.1 inhabitants per square kilometre (182/sq mi)	9	Until 1993, Ardabil was part of East Azerbaijan province.[7]	IranArdabil.png
...