本文主要是介绍d3成神之路(二):第二个柱状图,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
核心代码是理解
data(data)
join("rect")
.attr("height", d => yScale(0) - yScale(d.value))
const yScale = d3.scaleLinear().domain([0, d3.max(data, x => x.value)]).range([innerHeight, 0])
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>先做一个柱状图</title><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1" />
</head><body><svg width="800" height="800" id="main" class="svg"></svg><script src="https://cdn.jsdelivr.net/npm/d3@7.0.1/dist/d3.min.js"></script><script>const data = [{ name: 'a', value: 1 },{ name: 'b', value: 2 },{ name: 'c', value: 3 },{ name: 'd', value: 4 },{ name: 'e', value: 5 },]const svg = d3.select('#main');const width = svg.attr('width');const height = svg.attr('height');const margin = { top: 60, right: 30, bottom: 60, left: 50 }const innerWidth = width - margin.right - margin.leftconst innerHeight = height - margin.top - margin.bottomconst 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.left},${margin.top})`)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 bar = g.append("g").attr("fill", "steelblue").selectAll("rect").data(data).join("rect").style("mix-blend-mode", "multiply").attr("x", d => xScale(d.name)).attr("y", d => yScale(d.value)).attr("height", d => yScale(0) - yScale(d.value)).attr("width", xScale.bandwidth());</script>
</body></html>
这篇关于d3成神之路(二):第二个柱状图的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!