我试图将箱形图作为使用d3和AngularJS的数据可视化界面的一部分来实现。我正在使用这个盒子图包:https://bl.ocks.org/mbostock/4061502。
但是,我无法弄清楚示例代码的哪一部分控制了箱形图的位置。在该示例中,五个箱形图顺序排列。当我尝试生成我的情节时,它们都显示在彼此之上。
以下是我用来生成箱形图的代码:
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画布创建方式的代码。这是在角度指令中完成的:
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]);
编辑:还不完美,但到了那里:
答案 0 :(得分:2)
你需要的是一个有序的比例来定位父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:我目前无法测试代码,但它应该像描述的那样工作。