尝试使用 D3 在地图上显示条形图,结果为错误:属性 <rect> 高度:属性的意外结尾。预期长度," "



我是D3和Web开发的新手。我从 Elijah Meeks 那里复制了这段代码的一部分:http://bl.ocks.org/emeeks/4531633,他成功地在地图上显示代表数据的条形图,就像在地图上放置一个分散的条形图一样。

我正在从外部加载 JSON,在 JSON 中创建一个名为 drugDeath 的变量,并将 JSON 文件重命名为 .js。数据是巨大的,它代表了美国每个县的药物引起的死亡,从疾病预防控制中心获得。我正在尝试显示每个县的药物引起的死亡人数,并将此数字与地图上以县质心为中心的条形高度相关联。因此,有可能有数千个条形可以可视化。

数据的格式如下所示(您可以在此处看到它 https://github.com/allanrimban/allanrimban.github.io/tree/master/maps/drug_deaths_county(:

{
"X": -113.758151046471,
"Y": 35.7045834851058,
"GEOID": 4015,
"LONG": -113.7582,
"LAT": 35.7046,
"County": "Mohave County, AZ",
"Deaths": 63,
"Population": 205249,
"Crude Rate": 30.7,
"coordinates": "-113.7582,35.7046"
},
{
"X": -90.4054985445433,
"Y": 30.6267806285343,
"GEOID": 22105,
"LONG": -90.4055,
"LAT": 30.6268,
"County": "Tangipahoa Parish, LA",
"Deaths": 38,
"Population": 130710,
"Crude Rate": 29.1,
"coordinates": "-90.4055,30.6268"
},

我的代码在下面,但它什么也没做。页面上没有显示任何内容,只是全白。我错过了什么?D3 能否处理与 quetsion 中的文件一样大的文件? 我感谢任何反馈。谢谢。

<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<script src="https://d3js.org/d3.v5.js"></script>
<script src="https://d3js.org/topojson.v0.min.js"></script>
<script src="Drug_Deaths_County_Simple_JSON.js"></script>
</head>
<body>        
<script>
var width = 960, height = 960;
scaleVal = 1000;            
rotateVal = 30;
var svg = d3.select('body')
.append('svg')
.attr('width', width)
.attr('height', height);
projection = d3.geoAlbers()              
.scale(scaleVal)
.rotate([121.00, -35.50, 20])
.center([-4, 5]);

var geoPath = d3.geoPath()
.projection(projection);
bars = svg.selectAll("g")
.data(drugDeaths)
.enter()
.append("g")
.attr("class", "bars")
.attr("transform", function(d) {return "translate(" + projection(d.coordinates) + ")";});
bars.append("rect")               
.attr('height',  function(d) {return d.Deaths})
.attr('width', 1)
.attr('y', function(d) {return -(d.Deaths)})
.attr("class", "bars")
.style("fill", "green")
.style("stroke", "white")
.style("stroke-width", 2);
bars.transition().duration(500).style("opacity", 1)
d3.select(self.frameElement).style("height", height + "px");                            

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

如果您阅读文档 https://github.com/d3/d3-geo#_projection 您会看到不允许使用字符串。坐标必须是经度、纬度。

.attr("transform", function(d) {return "translate(" + projection([d.LONG, d.LAT]) + ")";});

由于某种原因,矩形在height中给出错误。设置.bars样式解决了这个问题。

bars.append("rect")
.attr('height', function(d) {return d.Deaths})
.attr('width', 2)
.attr('y', function(d) {return -(d.Deaths)})
.attr("class", "bars");

.CSS

.bars {
fill: green;
stroke: white;
stroke-width: 1;
}

最新更新