gpt4 book ai didi

javascript - 为什么我的 D3 堆积面积图翻转了?

转载 作者:行者123 更新时间:2023-11-30 09:59:07 25 4
gpt4 key购买 nike

我有一个应该如下所示的 D3 图表:

enter image description here

但它看起来像这样:

enter image description here

这是我正在使用的代码:

<!DOCTYPE html>
<meta charset="utf-8">
<head>

</head>
<body>
<svg id="chart"></svg>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script>
var NSW = "NSW";
var QLD = "QLD";

var width = 600;
var height = 400;
var years = [];

var getStat = function(year, volatility, basis) {
return {
d: year,
x: basis,
vol: volatility,
value: 45 * Math.pow(basis, year),
high: 45 * Math.pow(basis+volatility, year),
low: 45 * Math.pow(basis-volatility, year),
}
}

for(i = 0; i < 25; i++) {
years.push(i);
}

var data = years.map(function(year){ return [getStat(year, 0.03, 1.08),getStat(year, 0.02, 1.08), getStat(year, 0.01, 1.08)]; }); // generate bogus data
var set_one = data.map(function(d) { return d[0];});
var set_two = data.map(function(d) { return d[1];});
var set_three = data.map(function(d) { return d[2];});

var chart = d3.select("#chart").attr("width", width).attr("height", height).append("g");
var x = d3.scale.linear().domain([0, years.length]).range([0, width]);
var y = d3.scale.linear().domain([0, d3.max(data, function(d){ return Math.max(d[0].high, d[1].high); })]).range([0, height]);
var area = d3.svg.area().x(function(d,i) { return x(i); })
.y0(function(d, i){ return d.low}) //FUNCTION FOR BASE-Y
.y1(function(d, i){ return d.high * 0.99;}); //FUNCTION FOR TOP-Y

chart
.selectAll("path.area")
.data([set_one,set_two,set_three]) // !!! here i can pass both arrays in.
.enter()
.append("path")
.attr("fill", "rgba(0,0,0,0.5)")
.attr("class", function(d,i) { return [NSW,QLD,"T"][i]; })
.attr("d", area);

</script>

我做错了什么?

最佳答案

实际上,您没有做错任何事,y 轴从 0 开始向下,从上到下 height。所以要翻转它,您可以将 y 值设置为 height - yValue:

var area = d3.svg.area().x(function(d,i) { return x(i); })
.y0(function(d, i){ return (height - (d.low))}) //FUNCTION FOR BASE-Y
.y1(function(d, i){ return (height - (d.high * 0.99))}); //FUNCTION FOR TOP-Y

Fiddle Example

关于javascript - 为什么我的 D3 堆积面积图翻转了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32601898/

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