javascript - D3 矩形元素不显示

标签 javascript d3.js

我正在尝试使用 D3 版本 4.x.x 设置一个简单的条形图,但是,我相信我所做的一切都是正确的,但似乎无法显示矩形。我附上了一个代码笔来查看这一点。

提前感谢您解决导致此问题的任何菜鸟问题,因为我是 D3 的新手。 http://codepen.io/PizzaPokerGuy/pen/XpoJxG?editors=0111

enter code here//Width of svg, will be used again down the road
const width = 1000;
//Height of svg, will be used again down the road
const height = 800;
//Padding so things have room to be displayed within svg
const padding = 60;
//Create our SVG container
var svg = d3.select("body")
.append('svg')
.attr("width", width)
.attr("height", height);

//JSON Enter data
var data =      d3.json('https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/mast er/GDP-data.json',
  (error, data) => {
   var chartData = data.data;
   //Stores barWidth variable, math.ciel rounds up, used to set an equal width for each rect
  var barWidth = Math.ceil((width - padding) / chartData.length);
   //Define xScale
  const xScale = d3.scaleLinear()
  .domain([0, d3.max(chartData, (d) => d[0])])
  .range([padding, width - padding]);
  //Define yScale
const yScale = d3.scaleLinear()
  .domain([0, d3.max(chartData, (d) => d[1])])
  .range([height - padding, padding]);

//Selects SVG elements and selects all rect elements within it
svg.selectAll("rect")
  //Adds data to use later
  .data(chartData)
  //Allows us to add items to the dom if data is larger than ammoutn of rect elements selected
  .enter()
  //Adds rect element
  .append("rect")
  //Adds x attribute to x based off of d(chartData), need to create a date as a string is not enough
  .attr("x", (d) => xScale(new Date(d[0])))
  //Sets y attribute of rectangle
  .attr("y", (d) => yScale(d[1]))
  //Sets height, we minus the value from height to invert the bars
  .attr("height", (d) => height - yScale(d[1]))
  //sets width of rect elements
  .attr("width", barWidth)
  //fill in color of rects
  .attr("fill", "black");

});

最佳答案

您使用日期作为 X 轴,因此最好使用时间刻度而不是 scaleLinear

const xScale = d3.scaleTime()
    .domain(d3.extent(chartData, function(d) { return new Date(d[0]); }))
    .range([padding, width - padding]);

代码笔:http://codepen.io/anon/pen/egbGaJ?editors=0111

关于javascript - D3 矩形元素不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42193353/

相关文章:

javascript - D3 树链接箭头很奇怪,不在正确的位置。如何修复它们?

javascript - SVG 元素在变换后丢失事件监听器

javascript - Bcrypt 比较密码时给出 false

javascript - 将 jQuery 对话框附加到 Google map 标记中的 InfoBubble

javascript - 在 svg 图表顶部添加 div (D3.js)

d3.js - D3 示例不起作用

javascript - 当页面上的输入更改时,主干 View 事件不会触发

javascript - 从另一个网站连接到 Sharepoint

javascript - 在 D3 面积图中绘制线条

javascript - 未捕获的 TypeError : t. rgb 不是函数