D3条形图不显示数组中的第一个元素 [英] D3 bar chart not showing first element in array
问题描述
我正在制作第一套D3教程(此处),遇到一个问题,其中数据数组的第一项不会出现。我在每个数据元素上放置的边框表示本质上第一个条目已经折叠成顶部的行。是否有解释为什么会发生这种情况?如何解决这个问题?
I'm working on the first set of D3 tutorials (found here) and have run into a problem where the first item of the data array doesn't appear. The border i have placed on each data div element indicates that essentially that first entry has "collapsed" into a line up the top. Is there an explanation as to why this is happening? How can I fix this?
我的HTML,CSS和JS已放在 codepen 查看和编辑。
My HTML, CSS and JS has been put onto codepen to view and edit.
提前感谢!
孤立的JS:
var data = [10, 23, 14, 5, 6, 6, 6, 22, 17 ];
d3.select(".project")
.selectAll(".project__bar-chart")
.data(data)
.enter()
.append("div")
.attr("class", "project__bar-chart")
.style("width", function(d) {return d + "rem";})
.text(function(d) {return d;})
推荐答案
您的HTML中包含以下内容:
You have this in your HTML:
<div class="project">
<div class="project__bar-chart"></div>
</div>
因此,当你这样做:
d3.select(".project").selectAll(".project__bar-chart")
您在 selectAll
中选择一个先前存在的< div>
输入选择将有一个元素少(要阅读更多信息,请参阅SO Docs中的此示例:占位符在输入选择中的作用)
You are selecting one previously existing <div>
in your selectAll
, and your "enter" selection will have one element less (to read more about it, see this example at S.O. Docs: The role of placeholders in "enter" selections)
解决方法:删除类 project__bar-chart
下的div:
Solution: remove the div with class project__bar-chart
:
<div class="project">
//look Ma, no div
</div>
这是您的笔: https://codepen.io/anon/pen/bgKxXG?editors=1010
这里是一个Stack片段:
And here is a Stack snippet:
var data = [10, 23, 14, 5, 6, 6, 6, 22, 17 ]; //The data that we're working with
d3.select(".project") //bring our focus to the container containing this class
.selectAll(".project__bar-chart")
.data(data) //the data is in line 1
.enter()
.append("div") // Shove the data (defined in line 1) into the Div in the HTML
.attr("class", "project__bar-chart")
.style("width", function(d) {return d + "rem";})
//we're inserting a function in this style attribute to make sure that the width of the div reflects the value given.
.text(function(d) {return d;}) //this is what it will look like
.project {
color: black;
font: 1rem;
font-family: sans-serif;
margin: .1rem:;
text-align: right;
}
.project__bar-chart {
background: #be3c3c;
border: 1px solid #802828
}
<head>
<script src="https://d3js.org/d3.v4.js"></script>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<div class="project">
</div>
这篇关于D3条形图不显示数组中的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!