【问题标题】:D3 bar chart not showing first element in arrayD3条形图未显示数组中的第一个元素
【发布时间】:2017-06-22 21:13:16
【问题描述】:

我正在编写第一组 D3 教程(找到 here)并且遇到了数据数组的第一项不出现的问题。我在每个数据 div 元素上放置的边框表明基本上第一个条目已“折叠”成顶部的一行。有没有解释为什么会这样?我怎样才能解决这个问题?

我的 HTML、CSS 和 JS 已放到 codepen 上查看和编辑。

提前致谢!

隔离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;}) 

【问题讨论】:

  • 删除你的<div class="project">中的<div>

标签: javascript html css d3.js


【解决方案1】:

你的 HTML 中有这个:

<div class="project">
  <div class="project__bar-chart"></div>
</div>

因此,当你这样做时:

d3.select(".project").selectAll(".project__bar-chart")

您在selectAll 中选择了一个先前存在的&lt;div&gt;,并且您的“输入”选择将少一个元素。

解决方法:删除类project__bar-chart的div:

<div class="project">
    //look Ma, no div
</div>

这是你的笔:https://codepen.io/anon/pen/bgKxXG?editors=1010

这是一个 Stack sn-p:

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>

【讨论】:

  • 非常感谢!您链接的文档也很有帮助。
猜你喜欢
  • 1970-01-01
  • 2021-12-01
  • 2017-10-31
  • 2021-12-16
  • 1970-01-01
  • 2015-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多