Published
Edited
Aug 18, 2022
Insert cell
# 基础的折线图练习
Insert cell
fruits = [
{name: "🍊", count: 21},
{name: "🍇", count: 13},
{name: "🍏", count: 8},
{name: "🍌", count: 5},
{name: "🍐", count: 3},
{name: "🍋", count: 2},
{name: "🍎", count: 1},
{name: "🍉", count: 1}
]
Insert cell
x = d3.scaleBand().domain(fruits.map(d => d.name)).range([margin.left, width - margin.right]).padding(0.1)
Insert cell
y = d3.scaleLinear().domain([0, d3.max(fruits.map(d => d.count))]).range([height - margin.bottom, margin.top])
Insert cell
line = d3.line().x(d => x(d.name)).y(d => y(d.count))
Insert cell
htl.html`<svg viewBox="0 0 ${width} ${height}">
<g transform="translate(${x.bandwidth() / 2}, 0)">
<path d="${line(fruits)}" fill="none" stroke="steelblue" stroke-width="1.5" stroke-miterlimit="1" />
</g>
${d3.select(htl.svg`<g>`).call(axisBottom).node()}
${d3.select(htl.svg`<g>`).call(axisLeft).node()}
</svg>`
Insert cell
area = d3.area()
.x(d => x(d.name))
.y0(y(0))
.y1(d => y(d.count))
Insert cell
htl.html`<svg viewBox="0 0 ${width} ${height}">
<g transform="translate(${margin.left}, 0)">
<path d="${area(fruits)}" fill="steelblue" />
// 上下边线
<path d="${area.lineY0()(fruits)}" fill="none" stroke="red" stroke-width="2" />
<path d="${area.lineY1()(fruits)}" fill="none" stroke="red" stroke-width="2" />
// 左右边线
<path d="${d3.line().x(() => x(fruits[0].name)).y(d => y(d.count))([{count: 0}, fruits[0]])}" fill="none" stroke="red" stroke-width="2" />
<path d="${d3.line().x(() => x(fruits[fruits.length - 1].name)).y(d => y(d.count))([{count: 0}, fruits[fruits.length - 1]])}" fill="none" stroke="red" stroke-width="2" />
</g>
${d3.select(htl.svg`<g>`).call(axisBottom).node()}
${d3.select(htl.svg`<g>`).call(axisLeft).node()}
</svg>`
Insert cell
axisBottom = g => g.attr('transform', `translate(0, ${height - margin.bottom})`).call(d3.axisBottom(x))
Insert cell
axisLeft = g => g.attr('transform', `translate(${margin.left}, 0)`).call(d3.axisLeft(y))
Insert cell
width = 600
Insert cell
height = 300
Insert cell
margin = ({ top: 20, right: 20, bottom: 20, left: 20 })
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more