D3 Creating SVG Elements Based on Data| D3 Part4
Before we start the data bound to DOM element refer
- D3 Part 1 - SVG Shapes
- D3 Part 2- D3 + Angular 7 Integration
- D3 Part 3- D3 Data Bound to DOM Elements
Creating SVG Elements Based on Data
We are going to use D3.js to add SVG elements to a component based on data.creating circles using radius dataset
Radius Dataset
let radiusDS= [100, 60, 30];
SVG Circle Element
Creating a circle shape using below code , refer W3schools
<svg width="100" height="100">
<circle cx="50" cy="50" r="50" fill="red" />
</svg>
Basic Attributes of Circle element
cx: x-axis coordinate of the center of the circle.
cy: y-axis coordinate of the center of the circle.
r: radius of the circle.
The Circle element is going to create using D3's Data method
In my Angular 7 component has 2 Div elements with id circleelement,circleelementdatabound. Div circleelement is used for simple circle and circleelementdatabound used for D3 data bound method. follow the below steps
Step 1: Div element selected from angular's Component
let divelement = d3.select('#circleelement');
Step 2: SVG element added inside the selected div element
let svgelement = divelement.append('svg')
.attr('width', 100)
.attr('height', 100);
Step 3: Circle element added inside the selected SVG element
var circleelement = svgelement.append('circle')
.attr('cx', 50)
.attr('cy', 50)
.attr('r', 50)
.style('fill', 'red');
Step 4: now data bound to create SVG elements. Div element selected from angular's Component
let divcircleelementdatabound = d3.select('#circleelementdatabound');
Step 5: SVG element added inside the selected div element
let svgforcircleelements = divcircleelementdatabound.append('svg')
.attr('width', 200)
.attr('height', 200);
Step 6: Dataset Created for circle elements radius
let radiusDS= [100, 60, 30];
Step 7: Data-bound did as below using D3's data method
let circleelements = svgforcircleelements.selectAll('circle')Step 8: Run the project and see the result.
.data(radiusDS)
.enter()
.append('circle')
.attr('cx', 100)
.attr('cy', 100)
.attr('r', function (d) { return d; })
.style('fill', function (d) {
if ( d === 100) {
return 'red'
}else if (d=== 60) { return 'green'}
else if (d=== 30) { return 'yellow'}
});
Code Action @Stackblitz
0 Comments