d3钢筋需要从下往上移动

  • 本文关键字:移动 d3 javascript d3.js
  • 更新时间 :
  • 英文 :


这是一个d3条形图。

  1. 我正在尝试制作从底部向上生长的条形动画。如何实现
  2. 此外,如何使标签(即条形图的文本(位于条形图的顶部并随条形图移动

目前,条形图从顶部开始,一直下降到零。

d3.select("body")
.append("h2")
.text("BAR GRAPH");
const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
const w = 500;
const h = 120;
const svg = d3
.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var bars = svg
.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", (d, i) => i * 30)
.attr("y", (d, i) => h - 3 * d)
.attr("width", 25)
.attr("height", (d, i) => 3 * d)
.attr("fill", "navy");
bars
.transition()
.duration(400)
.attr("y", h)
.attr("height", (d, i) => 3 * d);
svg
.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(d => d)
.attr("x", (d, i) => i * 30)
.attr("y", (d, i) => h - 3 * d - 3)
.style("font-size", "25px")
.style("fill", "red")
.append("title")
.text(d => d);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

您的代码对条形图来说几乎是对的,您只需要将做作的顺序更改为条形图的y属性,并在开始时将条形图的高度属性设置为0。

我只是修改了你的例子中的三行,并用注释标记它们,以显示要更改什么才能达到你想要的效果。

要使标签跟随条形图,您只需在它们上添加一个具有相同持续时间的过渡即可!我在最后一块添加了一些行,并修改了一行以达到效果。

希望有帮助:(

d3.select("body")
.append("h2")
.text("BAR GRAPH");
const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
const w = 500;
const h = 120;
const svg = d3
.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var bars = svg
.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", (d, i) => i * 30)
.attr("y", h) // modified here
.attr("width", 25)
.attr("height", 0) // modified here
.attr("fill", "navy");
bars
.transition()
.duration(400)
.attr("y", (d, i) => h - 3 * d) // modified here
.attr("height", (d, i) => 3 * d);
// modified a bit here
var labels = svg
.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(d => d)
.attr("x", (d, i) => i * 30)
.attr("y", h) // modified here
.style("font-size", "25px")
.style("fill", "red");

labels
.append("title")
.text(d => d);

labels
.transition() // added here
.duration(400) // added here
.attr("y", (d, i) => h - 3 * d - 3) // added here
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

最新更新