gpt4 book ai didi

javascript - D3 JS 绘制条形图

转载 作者:行者123 更新时间:2023-11-28 19:46:13 25 4
gpt4 key购买 nike

我正在尝试使用 D3 在 JS 中绘制一些条形图。所以到目前为止我所做的是:

var svg = d3.select("body").append("svg").attr("width", 500).attr("height", 200);
svg.selectAll("rect").... //drawing the bars
svg.selectAll("text").... //putting labels on top of bars

但是当我尝试放置标签时,我需要它们位于条形的顶部中间。但要知道将它们放在哪里,我需要以某种方式引用这些 d3 对象作为条形...我该怎么做?

最佳答案

看一下:

每个都展示了如何定位标签。

例如,在每个水平条的末尾...

  // Create text values that go at end of each bar...
canvas.selectAll("text")
.data(dataSet) // Bind dataSet to text elements
.enter().append("svg:text") // Append text elements
.attr("x", x)
.attr("y", function(d, i) { return y(i); })
//.attr("y", function(d) { return y(d) + y.rangeBand() / 2; })
.attr("dx", function(d) { return x(d.magnitude) - 5; })
.attr("dy", barHeight-5) // vertical-align: middle
.attr("text-anchor", "end") // text-align: right
.text(function(d) { return d.magnitude;})
.attr("fill", "White");

或者每个竖条顶部的文本...

  // Create text values that go at top of each bar...
canvas.selectAll("text")
.data(dataSet) // Instruct to bind dataSet to text elements
.enter().append("svg:text") // Append text elements
// Identify root coordinate (x,y)
//.attr("x", function(d, i) { return x(i) + barWidth; }) // <-- Can't use because of bug in FireFox
.attr("x", function(d, i) { return x(i) + barWidth / 2; }) // <-- Using because of bug in Firefox
// Note: the following "+1" offset places value above bar in
// Space between the top of the bar and the top of the canvas.
.attr("y", function(d) {
return canvasHeight - y(d.magnitude ); })
//.attr("dx", -barWidth/2) // <-------------- Can't use because of bug in FireFox
.attr("dy", "1em") // Controls padding to place text above bars
.attr("text-anchor", "middle")
.text(function(d) { return d.magnitude;})
.attr("fill", "Black");

我希望这会有所帮助。

关于javascript - D3 JS 绘制条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24242722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com