[英]D3 scales mess up my bar chart
I'm writing a simple bar chart that draws a rect element for each piece of data.我正在编写一个简单的条形图,为每条数据绘制一个矩形元素。 This is a part of my code without scales, which works fine:这是我没有比例尺的代码的一部分,它工作正常:
const rect = svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", (d, i) => (i*4))
.attr("y", (d) => h - d[1]/50)
However, if I add y-scale, my bars flip over, and if I add x-scale, I can only see one bar.但是,如果我添加 y-scale,我的条会翻转,如果我添加 x-scale,我只能看到一个条。 Here's my code with scales:这是我的带有比例尺的代码:
const xScale = d3.scaleLinear()
.domain([0, d3.max(dataset, (d) => d[0])])
.range([padding, w - padding]);
const yScale = d3.scaleLinear()
.domain([0, d3.max(dataset, (d) => d[1])])
.range([h - padding, padding]);
//some other code
const rect = svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", (d, i) => xScale(i*4))
.attr("y", (d) => yScale(d[1]/50))
Here's my CodePen with scales, that's what it looks like: http://codepen.io/enk/pen/vgbvWq?editors=1111这是我的带有刻度的 CodePen,它看起来像: http ://codepen.io/enk/pen/vgbvWq?editors=1111
I'd be really greatful if somebody told me what am I doing wrong.如果有人告诉我我做错了什么,我会非常高兴。
D3 scales are not messing with your chart. D3 比例不会干扰您的图表。 The problem here is simple.这里的问题很简单。
Right now, this is your dataset:现在,这是您的数据集:
[["1947-01-01", 243.1], ...]
As you can see, d[0]
is a string (representing a date), not a number.如您所见, d[0]
是一个字符串(表示日期),而不是数字。 And, in d3.scaleLinear
, the domain is an array with two values only.而且,在d3.scaleLinear
,域是一个只有两个值的数组。
The solution here is using a scaleBand
instead:这里的解决方案是使用scaleBand
代替:
const xScale = d3.scaleBand()
.domain(dataset.map(d => d[0]))
.range([padding, w - padding]);
And changing the code of the rectangles to actually use the scales (I made several changes, check them):并更改矩形的代码以实际使用比例(我做了一些更改,检查它们):
const rect = svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("width", xScale.bandwidth())
.attr("x", (d => xScale(d[0]))) //xScale
.attr("height", (d => h - yScale(d[1]))) //yScale
.style("y", (d => yScale(d[1])))
.attr("data-date", (d) => d[0])
.attr("data-gdp", (d) => d[1])
.attr("class", 'bar')
Here is your updated CodePen: http://codepen.io/anon/pen/NdJGdo?editors=0010这是您更新的 CodePen: http ://codepen.io/anon/pen/NdJGdo?editors=0010
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.