我正在努力使用D3 v4创建条形图,以使用从XML HTTP Request中提取的数据绘制条形图。这是FreeCodeCamp的D3认证轨道中的第一个挑战:https://learn.freecodecamp.org/data-visualization/data-visualization-projects/visualize-data-with-a-bar-chart
我设法将数据作为JSON对象提取,并且可以使用D3进行遍历。 JSON对象如下所示:
{
"errors": {},
"id": 120140,
"source_name": "Federal Reserve Economic Data",
"source_code": "FRED",
"code": "GDP",
"name": "Gross Domestic Product, 1 Decimal",
"urlize_name": "Gross-Domestic-Product-1-Decimal",
"display_url": "http://research.stlouisfed.org/fred2/data/GDP.txt",
"description": "Units: Billions of Dollars\nSeasonal Adjustment: Seasonally Adjusted Annual Rate\nNotes: A Guide to the National Income and Product Accounts of the United States (NIPA) - (http://www.bea.gov/national/pdf/nipaguid.pdf)",
"updated_at": "2015-12-14T20:00:28.561Z",
"frequency": "quarterly",
"from_date": "1947-01-01",
"to_date": "2015-07-01",
"column_names": [
"DATE",
"VALUE"
],
"private": false,
"type": null,
"premium": false,
"data": [
[
"1947-01-01",
243.1
],
[
"1947-04-01",
246.3
],
[
"1947-07-01",
250.1
],
[
"1947-10-01",
260.3
],...}
"data": [],
是我要形象化的元素。
我设法使用数组中的整数(
“ 1947-01-01”,
243.1
]),但我正在努力地应用比例尺,以便在生成的图表中绘制图表。我尝试将d3.scalelinear()
用于x和y轴:
//setting the scales for the chart
const xScale = d3.scaleLinear()
.domain([0, d3.max(chart_data, (d) => d[0])])
.range([margin, width - margin]);
const yScale = d3.scaleLinear()
.domain([0, d3.max(chart_data, (d) => d[1])])
.range([height - margin, margin]);
但是当我尝试将xScale应用于图表的'x'属性或将yScale应用于te'height'属性时,会出现NaN错误。我不确定自己在做什么错。
我已将代码上传到JSFiddle:https://jsfiddle.net/siyafrica/r2wmxtpj/2/