I'm really struggling to understand d3's area
and stack
layout stuff. I tried making what I thought was the smallest example but nothing appears and in fact it prints errors in the console. What am I not getting? Here's the code.
var svg = d3.select("body").append("svg")
.attr("width", 400)
.attr("height", 300)
var testData = [
[ 0, 10],
[10, 20],
[20, 30],
[30, 20],
];
svg.selectAll("path.area")
.data(testData)
.enter().append("path")
.style("fill", "#ff0000")
.attr("d", d3.svg.area());
Visualizations typically consist of discrete graphical marks, such as symbols, arcs, lines and areas. While the rectangles of a bar chart may be easy enough to generate directly using SVG or Canvas, other shapes are complex, such as rounded annular sectors and centripetal Catmull–Rom splines.
D3 allows you to bind arbitrary data to a Document Object Model (DOM), and then apply data-driven transformations to the document. For example, you can use D3 to generate an HTML table from an array of numbers. Or, use the same data to create an interactive SVG bar chart with smooth transitions and interaction.
scaleBand() function in D3. js is used to construct a new band scale with the domain specified as an array of values and the range as the minimum and maximum extents of the bands. This function splits the range into n bands where n is the number of values in the domain array.
var circle = d3. selectAll("circle"); With a selection, we can make various changes to selected elements.
The dimension of the data is not correct. Each area path needs a 2D array, like this:
d3.svg.area()([[ 0, 10], [10, 20], [20, 30], [30, 20]])
results in:
"M0,10L10,20L20,30L30,20L30,0L20,0L10,0L0,0Z"
That means that you need to bind a 3D array to the selection. Each element (i.e. path) in the selection will then receive a 2D array.
var svg = d3.select("body").append("svg")
.attr("width", 400)
.attr("height", 300)
var testData = [
[ 0, 10],
[10, 20],
[20, 30],
[30, 20],
];
svg.selectAll("path.area")
.data([testData]) // dimension of data should be 3D
.enter().append("path")
.style("fill", "#ff0000")
.attr("class", "area") // not the cause of your problem
.attr("d", d3.svg.area());
Sometimes it's easier to picture what is going on by imagining that you would like to create multiple areas. Then it would look like:
var testData1 = [
[ 0, 10],
[10, 20],
[20, 30],
[30, 20],
];
var testData2 = [
[100, 110],
[110, 120],
[120, 130],
[130, 120],
];
svg.selectAll("path.area")
.data([testData1, testData2])
.enter().append("path")
.style("fill", "#ff0000")
.attr("class", "area")
.attr("d", d3.svg.area());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With