d3成神之路(二):第二个柱状图
【摘要】
核心代码是理解 data(data) join("rect") .attr("height", d => yScale(0) - yScale(d.value))
const yScale = d...
核心代码是理解
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.left
const innerHeight = height - margin.top - margin.bottom
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.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>
文章来源: fizzz.blog.csdn.net,作者:拿我格子衫来,版权归原作者所有,如需转载,请联系作者。
原文链接:fizzz.blog.csdn.net/article/details/120027659
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)