@brandy
To render object data in D3.js, you can follow these steps:
1 2 3 4 5 6 7 |
const svgWidth = 800; const svgHeight = 400; const svg = d3.select('body') .append('svg') .attr('width', svgWidth) .attr('height', svgHeight); |
1 2 3 4 5 |
const data = [ { name: 'John', age: 25 }, { name: 'Jane', age: 30 }, { name: 'Alice', age: 27 } ]; |
1 2 3 4 5 6 7 8 9 |
const rects = svg.selectAll('rect') .data(data) .enter() .append('rect') .attr('x', (d, i) => i * 100) .attr('y', (d) => svgHeight - d.age * 5) .attr('width', 50) .attr('height', (d) => d.age * 5) .attr('fill', 'blue'); |
In this example, we are creating a bar chart where each bar represents a person's age. We are using the age
property of each object in the data array to determine the height of each bar. You can customize the rendering logic according to your specific data and visualization requirements.
1 2 3 4 5 6 7 8 |
svg.selectAll('text') .data(data) .enter() .append('text') .text((d) => d.name) .attr('x', (d, i) => i * 100) .attr('y', svgHeight - 10) .attr('fill', 'black'); |
This snippet adds text labels to the bars indicating the name of each person.
By following these steps, you can render object data in D3.js and create interactive and visually appealing data visualizations.