使用D3.js给地图上色

3

我是一名 Javascript 和 D3.JS 的新手。我有一个创建地图的代码:

<!DOCTYPE html>
<meta charset="utf-8">
<style>

body{
    background-color:#0B3861;
}    
path {
  stroke: grey;
  stroke-width: 0.25px;
  fill: #dfdfdf;
}
</style>
<body>
<script src="d3.js"></script>
<script src="http://d3js.org/topojson.v0.min.js"></script>
<script>
var width = 1000,
    height = 600;

var projection = d3.geo.mercator()
    .center([-5,45])
    .scale(200)
    .rotate([0,0]);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

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

var g = svg.append("g");


     d3.json("https://gist.githubusercontent.com/d3noob/5193723/raw/6e1434b2c2de24aedde9bcfe35f6a267bd2c04f5/world-110m2.json", function(error, topology) {


    g.selectAll("path")
      .data(topojson.object(topology, topology.objects.countries)
      .geometries)
    .enter()
      .append("path")
      .attr("d", path)
});

</script>
</body>
</html>

现在我想将一些国家涂成红色,另一些涂成蓝色。 我有另一个类似于这样的CSV文件: 国家,情感
法国,1
美国,0
所以如果情感为1,我想用红色填充该国家。 能否有人帮忙? 谢谢。
皮埃尔
1个回答

2

您需要在路径中使用style

.style("fill", 'red');

将颜色随机设置为蓝色或红色:

const colors = ['white', 'blue', 'red'];

g.selectAll("path")
  .data(topojson.object(topology, topology.objects.countries)
  .geometries)
   .enter()
  .append("path")
  .attr("d", path)
  .style("fill", () => colors[Math.floor(Math.random() * 2) + 1]);

你的代码填充国家的Codepen


(此为原文,已翻译为通俗易懂的中文)

谢谢你的回答。如果我想使用另一个文件(例如csv文件)而不是math.random,其中包含两列id和color:84, 2。在这种情况下,我希望国家84的颜色为红色。 - Pierre Chemla
1
加载你的 csv 文件,然后映射你的数据并在 fill 中使用,例如 .style("fill", ( d ) => d.id === ? 'red' : 'blue') - Avraam Mavridis
准备您的数据作为不同的列表:[id1,color1],[id2,color2] ... 然后使用比例尺:global_colorScale = d3.scale.ordinal().domain(data.map(function(d) { return d.id;}));).range(data.map(function(d) { return d.color;}));) 然后 .style("fill", function(d) { return global_colorScale(d.id); }) - futu
对我来说,显示三种颜色的代码是 colors[Math.floor(Math.random() * 3)] - Massmaker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接