d3.js - How to divide a map into zipcodes using d3, javascript, and a json file? - Stack Overflow

I'm trying to create a nyc map with zipcode areas I can color in based on census data (like color

I'm trying to create a nyc map with zipcode areas I can color in based on census data (like color an area red if majority white or blue if majority nonwhite). I am simply using one of the shape files I found online from here ( ).

I converted the shp file to a geojson and then a topojson file.

I'd appreciate it if someone could look at my code below, and let me know how I can go about doing this.

Code:

<!DOCTYPE html>
<meta charset="utf-8">
<style>
</style>
<body>
<script src="//d3js/d3.v3.min.js" charset="utf-8"></script>
<script src="//d3js/topojson.v1.min.js"></script>

<script>

var width = 500,
    height = 500;

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

  var projection = d3.geo.albers()
   .center([0,40.7])
   .rotate([74,0])
   .translate([width/2,height/2])
   .scale(65000);

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

d3.json("zipcode.json", function(error, uk) {
    console.log(uk)
    console.log(uk.objects)
    console.log(uk.objects.zipcode)
  if (error) return console.error(error);
  var subunits = topojson.feature(uk, uk.objects.zipcode);

    svg.append("path")
        .datum(subunits)
        .attr("d", path);
});

Output:

The last part of my code (and the first part) is modeled after /. I understand I am trying to "Select All" of the some sort of feature array from the json file I am using in order to create paths. In my data, there's a coordinates array, which I am trying to access and use. My code doesn't throw any errors so I'm not sure where to look to debug.

Also, I'm I supposed to color the areas the paths create in this step or after I create the paths?

I'm trying to create a nyc map with zipcode areas I can color in based on census data (like color an area red if majority white or blue if majority nonwhite). I am simply using one of the shape files I found online from here ( https://data.cityofnewyork.us/Business/Zip-Code-Boundaries/i8iw-xf4u/data ).

I converted the shp file to a geojson and then a topojson file.

I'd appreciate it if someone could look at my code below, and let me know how I can go about doing this.

Code:

<!DOCTYPE html>
<meta charset="utf-8">
<style>
</style>
<body>
<script src="//d3js/d3.v3.min.js" charset="utf-8"></script>
<script src="//d3js/topojson.v1.min.js"></script>

<script>

var width = 500,
    height = 500;

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

  var projection = d3.geo.albers()
   .center([0,40.7])
   .rotate([74,0])
   .translate([width/2,height/2])
   .scale(65000);

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

d3.json("zipcode.json", function(error, uk) {
    console.log(uk)
    console.log(uk.objects)
    console.log(uk.objects.zipcode)
  if (error) return console.error(error);
  var subunits = topojson.feature(uk, uk.objects.zipcode);

    svg.append("path")
        .datum(subunits)
        .attr("d", path);
});

Output:

The last part of my code (and the first part) is modeled after https://bost.ocks/mike/map/. I understand I am trying to "Select All" of the some sort of feature array from the json file I am using in order to create paths. In my data, there's a coordinates array, which I am trying to access and use. My code doesn't throw any errors so I'm not sure where to look to debug.

Also, I'm I supposed to color the areas the paths create in this step or after I create the paths?

Share edited Mar 6, 2017 at 6:12 pr338 asked Mar 6, 2017 at 2:18 pr338pr338 9,19020 gold badges56 silver badges72 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

This answer uses d3 v3 and considers census tracts rather than zip codes (reflecting the original edit, but the principles remain the same)

The selection's role in adding features:

I understand I am trying to "Select All" of the some sort of feature array from the json file I am using in order to create paths.

Rather than selecting something from the json file, you are selecting elements in the DOM. D3 will bind the data in the json to the features where they exist, produce an enter() selection where they don't, and produce an exit() selection where there are excess DOM elements selected in relation to the json data.

This is why the initial appending of data with a selectAll(type).data(data) statement is followed with an .enter() statement generally. The enter returns the elements that must be added to the DOM:

svg.selectAll(".tract")
    // bind data to the selection
    .data(topojson.feature(uk, uk.objects.nyct2010).features)
  .enter()
    // set properties for the new elements:
    .append("path") 
    .attr("class", "tract")
    .attr("d", path);

If you were updating the data - say showing some year by year property in your maps, you wouldn't need the .enter() if the number of geographic features was constant (likely the case), you would just set the data and then modify the properties. If the number of elements in your new data array is the same as the old one, then the enter() selection will actually be empty.

The intial append with this method generally assumes the selectAll statement is empty, so that all items in the data are appended with the enter selection, this causes many people a lot of grief (a) (b) (c) (d) (e) (f).

When using the alternate approach:

svg.append('path')
  .datum(subunits)
  .attr('d',path')

You just append one path element enpassing all features, which makes styling individual areas impossible. In contrast, the top approach appends one path for each element in your json.

Setting map attributes:

You may have difficulty in setting the the class of each path to d.coordinates. Using topojson.feature(data, data.objects.features).features returns geojson from your topojson. The coordinates property of each feature is an array - which might not won't work with a class declaration.

But, you have the right approach. An inline function can set attributes easily:

var color = d3.scale.category20();

svg.selectAll("path")
  .data(subunits) // from the question code.
  .enter()
  .append('path')
  .attr('fill',function(d,i) { return color(i); })
  .attr("d", path);

Using this I get:

(block)

But, let's look at d in that inline function above ( .attr('fill',function(d,i) { console.log(d); return color(i); }) ). It is a geojson object:

Object { type: "Feature", properties: Object, geometry: Object }

If you don't see any properties (it'll always have a properties property, but it might be empty or contain only methods), you have some bad news, the properties are empty. Consequently, there are no properties containing data that can be displayed - eg coloring the map. There are also no identifiers in the data. This makes joining outside data to each feature impossible and there is no data in the feature to show. Topojson doesn't press properties so you should be able to see them if they are present in the text of the file:

..."Polygon","properties":{"CTLabel":"1223","BoroCode":"4","BoroName":"Queens","CT2010":"...

Showing properties of geographical features

You'll need to find a geographical dataset that has properties. Property-less features might be great for backgrounds, but less useful for everything else.

I found a source of the 2010 census tracts here. I downloaded the shapefile and converted it to topojson at mapshaper (be sure to copy all the files into the window - drag and drop - so that the data and the projection data is transfered). The data is already projected (to the New York State Plane), so you should unproject/'project' it to WGS84 by typing proj wgs84 in the console. This answer might help in terms of understanding projected/unprojected data and d3

The file I'm working with has the property BoroCode which I'll use to display in a choropleth type display:

svg.selectAll("path")
   .data(topojson.feature(data, data.objects.nyct2010).features)
   .enter()
   .append('path')
   .attr('fill',function(d) {return color(d.properties.BoroCode); })
   .attr("d", path);

This gives me:

(block)

Joining data to features

Many shapefiles, topojsons, geosjons, feature classes etc don't include many properties/attributes. These files containing geographic coordinates are often joined to files that contain properties/attributes (but no coordinates) in a data join based on an identifier shared in each data source.

There is an excellent example here on that in practice, though a better explanation might be here. I'll use the one of the few files I could find (relatively quickly and free) with census tract identifiers. Census information is generally great as it contains standardized identifiers. This file is a csv containing disposable ine data.

Now with the shared identifier, we can show the geographic shapes and assign colors to them based on the ine values in the csv.

Once both files are loaded, I'll make a dictionary:

var lookup = {};
ine.forEach(function(d) { lookup[d.tractID] = +d.disposable_ine; });

and then I'll show the features, almost the same as above:

svg.selectAll("path")
   .data(topojson.feature(data, data.objects.nyct2010).features)
   .enter()
   .append('path')
   .attr('fill',function(d) { return color(lookup[parseInt(d.properties.CT2010)] ); })
   .attr("d", path);

I used parseInt as I modified the csv's in Excel and lost the leading zeros in the csv, parseInt drops the leading zeros from my geojson identifiers.

The end result looks something like:

(block)

If you took a look at the block, you'll see I nested d3.csv inside the d3.json callback function. Each of these is asynchronous, so unless we use a library like queue.js we'll need to wait until the json is loaded before loading the csv. This nested approach solves the problem of potentially styling the features before the csv is loaded

This should cover how to color a map either based on increment, property within the geo/topo json and/or by joining the data from a non-spatial source to the spatial shapes. See the blocks for the implementation of a color scale, without a proper scale color(i) won't return anything.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743775175a4505093.html

相关推荐

  • VMware虚拟机设置为固定IP

    操作原因:安装完成虚拟机后会生成一个IP,由于ip变化导致搭建好的k8s集群无法启动。因此将虚拟机配置为固定IP1、修改虚拟网络编辑器:打开虚拟网络编辑器,修改NAT设置:2、修改电脑的虚拟网卡地址选中这个网卡-->点击右键-->

    1小时前
    00
  • 《特斯拉Optimus Gen

    特斯拉推出的Optimus Gen - 2,凭借其多模态感知技术,成为了这场变革中的焦点,为机器人具身智能的发展开辟了全新道路。 想象一下,人类在与世界互动时,并非依赖单一感官,而是通过视觉、听觉、触觉等多种感官协同工作,从而对周围环境形成

    58分钟前
    00
  • Power BI Vega 条形纵向折线组合图表

    条形图和纵向折线图组合常用来展示绝对值和率值的组合。之前在知识星球分享过SVG的版本(使用内置表格加载),今天换一种实现方式,使用Deneb视觉对象:把需要展示的维度和指标拖拽到Deneb,本例维度为城市,绝对值为[kpi]度量值,率值为[

    53分钟前
    00
  • DeepSeek辅助Power BI自定义Vega条形图

    Power BI Deneb这个视觉对象支持Vega自定义图表。网上有丰富的Vega代码资源,参考《Power BI Deneb图表资源库》,EasyShu提供了Excel版本的Vega图表库,Power BI也可以借鉴。使用Vega并不意

    52分钟前
    00
  • 完美解决win7系统使用wireshark未响应问题

    Win7系统&#xff0c;安装wireshark4.0的版本&#xff0c;发现打开可以打开&#xff0c;但是只要点击网卡之后就会显示无响应 一开始我以为是位数的原因&#xff0c;之前用的64位的&am

    51分钟前
    00
  • 你的服务器够快吗?一文说清如何衡量服务器的性能?

    本文以一个标准的 Seurat 单细胞分析流程为例,深入探讨衡量计算性能的关键指标——运行时间(Elapsed Time)、CPU 时间(CPU Time)和等待时间(Wait Time)——揭示它们在单线程与多线程环境下的差异及其反映的系

    50分钟前
    00
  • windows7删除正在计算机,win7系统删除文件提示“正在准备再循环”的解决教程

    有时候可能会遇到win7系统删除文件提示“正在准备再循环”的问题&#xff0c;如果我们遇到了win7系统删除文件提示“正在准备再循环”的问题&#xff0c;要怎么处理win7系统删除文件提示“正在准备再循环”呢&#

    48分钟前
    00
  • 8.6K star!完全免费+本地运行+无需GPU,这款AI搜索聚合神器绝了!

    嗨,大家好,我是小华同学,关注我们获得“最新、最全、最优质”开源项目和高效工作学习方法 FreeAskInternet是一款革命性的开源项目,它完美结合了多引擎搜索和智能语言模型,让你在不联网、不花钱、不暴露隐私的情况下,获得媲美ChatG

    48分钟前
    00
  • 基于PacBio HiFi数据的人类全基因组重测序变异分析流程

    随着第三代测序技术,特别是PacBio HiFi(High Fidelity)测序技术的发展,我们能够获得兼具长读长和高准确度的测序数据。这为人类全基因组重测序(WGS)分析,尤其是复杂区域和结构性变异(Structural Variati

    47分钟前
    00
  • 瞧瞧别人家的日期处理,那叫一个优雅!

    前言在我们的日常工作中,需要经常处理各种格式,各种类似的的日期或者时间。比如:2025-04-21、20250421、2025年04月21日等等。有些字段是String类型,有些是Date类型,有些是Long类型。如果不同的数据类型,经

    45分钟前
    00
  • 皮尔兹Pnoz c1c2安全继电器配置与接线

    PNOZ compact是皮尔兹的一款经济型的安全继电器系列,价格实惠,空间紧凑,适用于安装急停按钮、安全门或光障光栅 等安全产品。PNOZ C1是适用急停按钮或安全门开关。PNOZ C2用于 4 类光障或带 OSSD 输出的传感器的安全

    38分钟前
    00
  • lenovo联想拯救者Legion Y9000P 2022款2023款2024款笔记本电脑(82RF,82WK,82WQ,83DE,83DF)原装出厂Windows11预装OEM系统镜像下载

    拯救者Legion Y9000P IAH7H 2022款【82RF】原厂Win11系统包 链接&#xff1a;https:pan.baidus1HYN4eO6eWCkgdP6ZxsjnmA?pwdnqw8  提取码&am

    37分钟前
    00
  • CMeas度量体系建设:让数据驱动更科学

    本文来自腾讯蓝鲸智云社区用户: CanWay研发效能度量在企业数字化转型中至关重要。它有助于企业全面量化研发过程,洞察业务绩效,识别效能瓶颈或提效机会、优化资源配置,并为决策提供有力支撑,持续推动企业研发效能优化提升。目前,效能度量已不局限

    35分钟前
    00
  • KB2533623补丁安装指南 - 解决Win7下无法运行.NET 67 WinForm应用

    KB2533623补丁安装指南 - 解决Win7下无法运行.NET 67 WinForm应用 项目地址:https:gitcodeopen-source-toolkit62304 概览 对于所有遇到Windows 7系统无法

    34分钟前
    00
  • Fabric8 Kubernetes 日志工具实践

    最近在使用 Fabric8 Kubernetes Client 的过程中发现了新大陆一样,感觉利用这个库可以进行很多有趣的功能尝试,其中一个便是日志的本地化。原因无他,rancher 页面性能实在太差了,经常性的暂停工作,碰到故障排查的时候

    33分钟前
    00
  • Sentinel 的熔断和限流

    在分布式系统里,服务之间牵一发而动全身,一个接口雪崩,可能带崩整个应用链路。要想系统抗住流量洪峰,顶住突发异常,就得在稳定性上下功夫。今天我就来说说稳定性保障里的老将——Sentinel,看看它是怎么凭借限流熔断,在服务治理的江湖里占得一席

    31分钟前
    00
  • AI|微信又又又有大动作了,直接把Deepseek变成了你的微信好友!

    腾讯又又又放大招了!在全球都在AI的浪潮中,以及年初Deepseek横空出世,使得中国的AI开始“吊打”海外的AI后,国内的AI使用也如雨后春笋般层出不穷。但是对于很多人来说AI的使用依然是一个门槛儿,手机上需要安装APP或者各种小程序跳转

    16分钟前
    20
  • OFC 2025 TeraHop报告:AI数据中心光连接技术

    在人工智能技术快速发展的背景下,AI数据中心的建设对光模块技术提出了更高要求。TeraHop在OFC 2025会议上的报告,深入探讨了这一领域的现状与未来。一、AI数据中心光互连面临的挑战(一)传输速率升级加速过去光

    13分钟前
    00
  • MCE干货分享

    在蛋白功能研究中,亲和力测定是揭示分子互作机制的关键环节。然而,传统方法通常依赖高纯度蛋白,而许多蛋白如膜蛋白、低溶解度蛋白等的研究就受到了限制。微量热泳动技术 (MST) 以其高灵敏度、低样本需求和对粗样品的兼容性,不仅可以检测重组蛋白,

    9分钟前
    00
  • CICD界一颗冉冉升起的新星,主打一个各种可以

    介绍在云计算与容器化技术高速发展的当下,多服务器环境下的软件构建与部署效率已成为开发者亟待突破的瓶颈。Komodo作为开源工具领域的革新者,凭借其高度灵活性、无限扩展潜力及人性化设计,为DevOps团队与独立开发者提供了全链路的解决方案。这

    6分钟前
    00

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信