d3成神之路(三):折线图
【摘要】
<!DOCTYPE html>
<html>
<head>
<title>先做一个柱状图</title>
</head&g...
<!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>
文章来源: fizzz.blog.csdn.net,作者:拿我格子衫来,版权归原作者所有,如需转载,请联系作者。
原文链接:fizzz.blog.csdn.net/article/details/120049904
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)