gpt4 book ai didi

javascript - box.js 的 d3.js 箱线图定位问题

转载 作者:行者123 更新时间:2023-11-30 15:28:54 25 4
gpt4 key购买 nike

我正在尝试将箱形图作为使用 d3 和 AngularJS 的数据可视化界面的一部分来实现。我正在使用这个箱形图包:https://bl.ocks.org/mbostock/4061502 .

但是,我无法弄清楚示例代码的哪一部分控制了箱形图的定位。在示例中,五个箱线图按顺序排列。当我尝试生成我的绘图时,它们全部出现在彼此之上。

enter image description here

这是我用来生成箱线图的代码:

            boxplots = svg.selectAll("svg")
.data(boxPlotData)
.enter().append("svg")
.attr("class", "box")
.attr("width", boxWidth + margin.left + margin.right)
.attr("height", boxHeight + margin.bottom + margin.top)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(chart);

这是创建 svg Canvas 的代码。这是在 Angular Directive(指令)中完成的:

template:"<svg width='825' height='600'></svg>",
link: function($scope, elem){

var d3 = $window.d3;
var rawSvg=elem.find('svg'); // this is the svg created in the template

var width = rawSvg[0].attributes[0].value;
var height = rawSvg[0].attributes[1].value;

var svg = d3.select(rawSvg[0]);

编辑:还不完美,但已经到了:

enter image description here

最佳答案

您需要的是一个序号比例尺,用于在父 svg 中定位框的 svg 元素。假设 width 表示父 svg 元素的宽度,data 是数据元素的数组,您可以使用它来创建比例:

const x = d3.scaleBand()
.range( [0, width] )
.domain( data.map( (el,i) => i ) );

在您现在可以使用的 svg 创建中

boxplots = svg.selectAll("svg")
.data(boxPlotData)
.enter().append("svg")
.attr( "x", (d,i) => x(i) ) // this is added
.attr("class", "box")
.attr("width", boxWidth + margin.left + margin.right)
.attr("height", boxHeight + margin.bottom + margin.top)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(chart);

PS:这假设您使用 d3js 的 v4。 v3 中的比例语法不同。

PPS:我目前无法测试代码,但它应该像描述的那样工作。

关于javascript - box.js 的 d3.js 箱线图定位问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42541705/

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