【发布时间】:2017-10-01 18:50:34
【问题描述】:
这真的让我很吃力。我正在尝试生成一个条形图来学习 d3.js。一切都很顺利,因为我慢慢地做事。第 1 天用于画布,第 2 天用于条形图,第 3 天用于缩放/边距等。直到今天,当我想添加一个轴时。为了让一切更容易可视化,我删除了主画布的笔触(在添加轴之前它显示得非常好)。
添加轴后,笔画被添加到条形图上,而不是包含所有内容的主 svg。我查看了我的代码 100 次,我确信没有任何问题,但结果却不是我所期望的。有什么线索吗?
- 没有指向图表任何元素的 css 链接,一切都是由 d3.js 生成的
- 在控制台中查看,笔划显示为主 svg(容器)的属性,但似乎该属性被忽略了
https://jsfiddle.net/vtw6pfwq/(我不得不更改数据集,但它可以工作)
<div class="datavis">
</div>
<script>
d3.csv("data/demo.csv", function(data) {
console.log(data);
var margin = {top: 20, right: 20, bottom: 20, left: 60};
var width = 750 - margin.left - margin.right;
var height = 250 - margin.top - margin.bottom;
var extent = d3.extent(data, function(d) {return +d.arg3;});
var scale = d3.scaleLog().domain(extent).range([height, 0]);
var yAxis = d3.axisRight(scale).ticks(5, "d");
d3.select(".datavis")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.style("stroke", "#BDBDBD") // this is the non-working line, as you can tell, the stroke is applied to the green bars, not the main svg. Why??
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.select("svg")
.append("g")
.attr("id", "yAxisG")
.attr("transform", "translate(0," + margin.top + ")")
.call(yAxis)
d3.select("g").selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", function(d,i) {return i * width / data.length;})
.attr("y", function(d) {return height-scale(d.arg3);})
.attr("width", function(d) {return width / data.length - 1;})
.attr("height", function(d) {return scale(d.arg3);})
.style("fill", "#4CAF50")
.style("opacity", function(d) {return d.arg2;});
});
</script>
【问题讨论】:
-
你会做小提琴吗?很难这样回答
-
嗨。是的,我做到了,对此感到抱歉,我是新来的。链接在主帖中。谢谢!