课程链接
Curran的课程,通过 D3.js 的 scaleLinear, max, scaleBand, axisLeft, axisBottom,根据 .csv 文件生成一个横向柱状图。
【注】如果想造csv数据,可以使用通义千问,关于LinearScale与BandScale不懂的地方也可以在通义千问里提问
https://tongyi.aliyun.com/qianwen/
Linear Scale (线性比例尺)
定义: 线性比例尺是一种将输入域(通常是数值范围)线性地映射到输出范围的比例尺。它非常适合处理连续的数值数据。(大体就是处理数据)
Band Scale (带状比例尺)
定义: 带状比例尺是一种将输入域(通常是离散的类别值)映射到输出范围的比例尺。它主要用于处理分类数据,常用于条形图的 x 轴或 y 轴。(大体就是处理文字、名称)
【data.csv】
country,population
China,1415046
India,1354052
United States,326767
Indonaesia,266795
Brazil,210868
Pakistan,200814
Nigeria,195875
Bangladesh,166368
Russia,143965
Mexico,130759
【pokemon.csv】
Rank,Pokemon,Type,Base_Attack
1,Kommo-o,Dragon/Fighting,165
2,Kyurem-Black,Dragon/Ice,170
3,Groudon,Ground,180
4,Kyogre,Water,150
5,Deoxys-Attack Forme,Psychic,180
6,Mega Rayquaza,Dragon/Flying,180
7,Xerneas,Fairy,130
8,Yveltal,Dark/Flying,130
9,Mewtwo-Mega X,Psychic/Fighting,190
10,Zekrom,Dragon/Electric,170
【style.css】
body {
margin: 0;
overflow: hidden;
}
rect {
fill: steelblue
}
text {
font-size: 1.4em;
}
【index.html】
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="./style.css">
<script src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/d3/5.6.0/d3.min.js"
type="application/javascript"></script>
</head>
<body>
<svg width="960" height="500"></svg>
<script>
const select = d3.select
const csv = d3.csv
const scaleLinear = d3.scaleLinear
const max = d3.max
const scaleBand = d3.scaleBand
const axisLeft = d3.axisLeft
const axisBottom = d3.axisBottom
const svg = select('svg')
const width = +svg.attr('width')
const height = +svg.attr('height')
const render = data => {
// const xValue = d => d.population;
// const yValue = d => d.country;
const xValue = d => d.Base_Attack;
const yValue = d => d.Pokemon;
const margin = {
top: 20,
right: 40,
bottom: 20,
left: 160
}
const innerWidth = width - margin.left - margin.right
const innerHeight = height - margin.top - margin.bottom
const xScale = scaleLinear()
.domain([0, max(data, xValue)])
.range([0, innerWidth])
const yScale = scaleBand()
.domain(data.map(yValue))
.range([0, innerHeight])
.padding(0.1)
// const yAxis = axisLeft(yScale)
const g = svg.append('g')
.attr('transform', `translate(${margin.left},${margin.top})`)
// yAxis(g.append('g')) // 添加Y轴
// 添加Y轴
g.append('g').call(axisLeft(yScale))
// 添加X轴
g.append('g').call(axisBottom(xScale))
.attr('transform',`translate(0,${innerHeight})`)
g.selectAll('rect').data(data)
.enter().append('rect')
.attr('y', d => yScale(yValue(d)))
.attr('width', d => xScale(xValue(d)))
.attr('height', yScale.bandwidth())
}
csv('./data.csv').then(data => {
data.forEach(d => {
d.population = + d.population * 1000;
});
// console.log(data);
render(data)
})
</script>
</body>
</html>