gpt4 book ai didi

javascript - D3js 中双重贷款表示的可行性

转载 作者:太空宇宙 更新时间:2023-11-04 15:30:30 25 4
gpt4 key购买 nike

是否可以在 d3js 中做这样的事情,以及如何做?

enter image description here

如果没有,是否有另一个 js 库可以做到这一点?

谢谢!

最佳答案

为了创建所需的数据可视化,您必须对两个轴使用线性比例:

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>

关于javascript - D3js 中双重贷款表示的可行性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44828400/

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