Draw a graph in React using d3.js
-
The introduction of d3
import * as d3 from 'd3';
import { select } from 'd3-selection';
-
Add SVG to the DOM
const svg = d3.select('#line3')
.append('svg')
.attr('width'.500)
.attr('height'.400)
.style('border'.'1px solid steelblue');
Copy the code
- Add x and y axes
const y = d3.scaleLinear()
.domain([0.100])
.range([370.20]);
const x = d3.scalePoint()
.domain(['Shanghai'.'shenzhen'.'hangzhou'.'the zhuhai'.'in suzhou'.'sun'.'wuxi'.'nanjing'.'Hong Kong'])
.range([0.400]);
svg.append('g')
.attr('transform'.'translate(30, 0)')
.call(d3.axisLeft(y));
svg.append('g')
.attr('transform'.'translate(30, 370)')
.call(d3.axisBottom(x));
Copy the code
- drawing
const line = d3.line()
// Change the line graph to a curve
.curve(d3.curveCatmullRom.alpha(0.5));
const list = [
[30.340], [80.320], [130.330], [180.310],
[230.330], [280.310], [330.350], [380.330], [430.360]]; svg.append('path')
.attr('d', line(list))
.attr('stroke'.'steelblue')
.attr('fill'.'none');
Copy the code
- rendering