代码语言:javascript复制
<!DOCTYPE html>
<html>
<head>
<title>先做一个柱状图</title>
</head>
<body>
<svg id="main" width="500" height="500"></svg>
<script src="https://cdn.jsdelivr.net/npm/d3@7.0.1/dist/d3.min.js"></script>
<script>
const svg = d3.select("#main")
const margin = { top: 30, right: 30, bottom: 30, left: 30 }
const width = svg.attr('width')
const height = svg.attr('height')
const data = [
{ name: 'a', value: 1 },
{ name: 'b', value: 2 },
{ name: 'c', value: 3 },
{ name: 'd', value: 4 },
{ name: 'e', value: 5 },
]
const innerHeight = height - margin.top - margin.bottom
const innerWidth = width - margin.left - margin.right
const xScale = d3.scaleBand()
.domain(data.map(x => x.name))
.range([0, innerWidth])
.padding(0.5)
const yScale = d3.scaleLinear()
.domain([0, d3.max(data, x=>x.value)])
.range([innerHeight, 0])
const g = svg.append('g')
.attr('id', 'maingroup')
.attr('transform', `translate(${margin.top}, ${margin.left})`)
const yAxis = d3.axisLeft(yScale)
g.append('g').call(yAxis)
const xAxis = d3.axisBottom(xScale)
g.append('g').call(xAxis).attr('transform',`translate(0, ${innerHeight})`)
const line = d3.line()
.defined(d => !isNaN(d.value))
.x(d => xScale(d.name))
.y(d => yScale(d.value))
g.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 1.5)
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.attr('d', line)
</script>
</body>
</html>