Data join with array of objects.
From D3 in Depth book by Peter Cook.
| license: gpl-3.0 | |
| height: 170 | |
| border: no |
Data join with array of objects.
From D3 in Depth book by Peter Cook.
| <!DOCTYPE html> | |
| <meta charset="utf-8"> | |
| <head> | |
| <title>Data join with array of objects</title> | |
| </head> | |
| <style> | |
| body { | |
| font-family: "Helvetica Neue", Helvetica, sans-serif; | |
| font-size: 12px; | |
| color: #333; | |
| } | |
| rect { | |
| fill: steelblue; | |
| } | |
| rect:hover { | |
| fill: orange; | |
| } | |
| text { | |
| text-anchor: end; | |
| } | |
| </style> | |
| <body> | |
| <svg width="760" height="140"> | |
| <g transform="translate(70, 30)"> | |
| <rect /> | |
| <rect /> | |
| <rect /> | |
| <rect /> | |
| <rect /> | |
| </g> | |
| <g transform="translate(70, 30)"> | |
| <text /> | |
| <text /> | |
| <text /> | |
| <text /> | |
| <text /> | |
| </g> | |
| </svg> | |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script> | |
| <script> | |
| var cities = [ | |
| { name: 'London', population: 8674000}, | |
| { name: 'New York', population: 8406000}, | |
| { name: 'Sydney', population: 4293000}, | |
| { name: 'Paris', population: 2244000}, | |
| { name: 'Beijing', population: 11510000} | |
| ]; | |
| // Join cities to rect elements and modify height, width and position | |
| d3.selectAll('rect') | |
| .data(cities) | |
| .attr('height', 19) | |
| .attr('width', function(d) { | |
| var scaleFactor = 0.00004; | |
| return d.population * scaleFactor; | |
| }) | |
| .attr('y', function(d, i) { | |
| return i * 20; | |
| }) | |
| // Join cities to text elements and modify content and position | |
| d3.selectAll('text') | |
| .data(cities) | |
| .attr('y', function(d, i) { | |
| return i * 20 + 13; | |
| }) | |
| .attr('x', -4) | |
| .text(function(d) { | |
| return d.name; | |
| }); | |
| </script> | |
| </body> | |
| </html> |