gpt4 book ai didi

javascript - 如何使用 d3.js 在 areaplot 中设置颜色和网格?

转载 作者:行者123 更新时间:2023-11-30 16:02:09 26 4
gpt4 key购买 nike

我有以下代码:

<!DOCTYPE html>
<html>
<head>
<title>areaplot</title>
<script src="http://d3js.org/d3.v3.min.js"></script>
<style>
svg { border: 1px solid #dedede; }

.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}

.area { fill: skyblue; }
</style>
</head>
<body>
<svg id="area" />
<script>
d3.csv("performance.csv", function (error, data) {

data.forEach(function (d) {
d.stocks = +d.stocks;
});
var margin = {top: 20, right: 20, bottom: 40, left: 50},
width = 575 - margin.left - margin.right,
height = 350 - margin.top - margin.bottom;
var x = d3.scale.linear()
.domain([d3.min(data, function (d) {
return d.percentage;
}), d3.min(data, function (d) {
return d.percentage;
})])
.range([0, width]);

var y = d3.scale.linear()
.domain([0, d3.max(data, function (d) {
return d.stocks;
})])
.range([height, 0]);

var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");

var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var area = d3.svg.area()
.x(function (d) {
return x(d.percentage);
})
.y0(height)
.y1(function (d) {
return y(d.stocks);
});
var svg = d3.select("svg#area")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("path")
.datum(data)
.attr("class", "area")
.attr("d", area);

svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);

svg.append("g")
.attr("class", "y axis")
.call(yAxis);

});


</script>
</body>
</html>

我必须将网格和颜色设置为与这张图片中的一样:

areaplot pic

我的 CSV 文件包含以下数据:

stocks,percentage
400,100
300,75
200,70
100,50
75,20

如何添加网格并使用 d3 设置颜色。

最佳答案

您可以使用线性渐变来实现这一点。

  var gradient = d3.select("svg").append("defs")
.append("linearGradient")
.attr("id", "gradient")
.attr("spreadMethod", "pad");
//start color white
gradient.append("stop")
.attr("offset", "0%")
.attr("stop-color", "white")
.attr("stop-opacity", 1);
//end color steel blue
gradient.append("stop")
.attr("offset", "90%")
.attr("stop-color", "steelblue")
.attr("stop-opacity", 1);

在区域路径上:

  svg.append("path")
.datum(data)
.style("fill", "url(#gradient)")//set the fill to the gradient id created above.
.attr("d", area);

工作代码 here

关于javascript - 如何使用 d3.js 在 areaplot 中设置颜色和网格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37564014/

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