I have the following code:
<!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>
I have to set the grid and the colors to look the same as in this picture:
My CSV file contains the following data:
stocks,percentage
400,100
300,75
200,70
100,50
75,20
How do I add the grid and set the colors using d3.
You can achieve this using linear gradient.
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);
On the area path:
svg.append("path")
.datum(data)
.style("fill", "url(#gradient)")//set the fill to the gradient id created above.
.attr("d", area);
Working code here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.