是否可以在d3js中执行类似的操作?
如果不是,是否还有另一个js库可以执行此操作?
谢谢 !
最佳答案
为了创建所需的dataviz,必须对两个轴都使用线性比例尺:
var x = d3.scaleLinear().range([0, width]),
y = d3.scaleLinear().range([height, 0]);
对于域,我添加50%(即乘以1.5),以获得更好的视觉效果:
x.domain([0, d3.max(data, function(d) {
return d.duration;
}) * 1.5]);
y.domain([0, d3.max(data, function(d) {
return d.monthly;
}) * 1.5]);
然后,使用它来附加矩形:
var bars = g.selectAll(null)
.data(data)
.enter()
.append("rect")
.attr("width", function(d) {
return x(d.duration);
})
.attr("height", function(d) {
return height - y(d.monthly);
})
.attr("x", 0)
.attr("y", function(d) {
return y(d.monthly);
})
.attr("fill", function(d) {
return colours(d.duration);
});
请记住:要使此方法起作用,较小矩形的数据必须紧随较大矩形的数据之后。
这是工作示例:
var svg = d3.select("svg"),
margin = {
top: 20,
right: 20,
bottom: 30,
left: 50
},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;
var x = d3.scaleLinear().range([0, width]),
y = d3.scaleLinear().range([height, 0]);
var colours = d3.scaleOrdinal(d3.schemeCategory10);
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var data = [{
monthly: 1258.5,
duration: 212
}, {
monthly: 1058.5,
duration: 120
}];
x.domain([0, d3.max(data, function(d) {
return d.duration;
}) * 1.5]);
y.domain([0, d3.max(data, function(d) {
return d.monthly;
}) * 1.5]);
var bars = g.selectAll(null)
.data(data)
.enter()
.append("rect")
.attr("width", function(d) {
return x(d.duration);
})
.attr("height", function(d) {
return height - y(d.monthly);
})
.attr("x", 0)
.attr("y", function(d) {
return y(d.monthly);
})
.attr("fill", function(d) {
return colours(d.duration);
});
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
g.append("g")
.attr("class", "axis axis--y")
.call(d3.axisLeft(y).ticks(5)
.tickSizeInner([-width]))
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.attr("fill", "#5D6971")
.text("Average House Price - (£)");
body {
background-color: #F1F3F3
}
.axis {
font: 15px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #D4D8DA;
stroke-width: 1px;
shape-rendering: crispEdges;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.1/d3.min.js"></script>
<svg width="600" height="400"></svg>