Published
Edited
May 5, 2021
Insert cell
Insert cell
data = [
{ name: '之前收入', price: 7000 },
{ name: '之後收入', price: 12000 },
];
Insert cell
chart = {
const svg = d3.create("svg")
.attr('viewBox', [0, 0, svgWidth, svgHeight])
.attr('height', svgHeight)
.attr('width', svgWidth);
const graph = svg
.append('g')
.attr('height', graphHeight)
.attr('width', graphWidth)
.attr(
'transform',
`translate(${(svgWidth - graphWidth) / 2}, ${
(svgHeight - graphHeight) / 2
})`,
);
graph
.selectAll('rect')
.data(data)
.join('rect')
.attr('width', x.bandwidth)
.attr('height', (d) => graphHeight - y(d.price))
.attr('x', (d) => x(d.name))
.attr('y', (d) => y(d.price))
.attr('fill', 'green')
.on('mouseover', function (e, d, i) {
tooltip
.html(
`<div>${d.name}</div>`)
.style('visibility', 'visible');

d3.select(this).attr('fill', 'blue');
})
.on('mousemove', function (e) {
tooltip
.style('top', e.pageY + 10 + 'px')
.style('left', e.pageX + 10 + 'px');
})
.on('mouseout', function () {
tooltip.html(``).style('visibility', 'hidden');
d3.select(this).transition().attr('fill', 'green');
});
svg
.append('g')
.attr(
'transform',
`translate(${graphMarginLeft}, ${graphMarginTop})`,
)
.call(yAxis);

svg
.append('g')
.attr(
'transform',
`translate(${graphMarginLeft}, ${
svgHeight - graphMarginTop
})`,
)
.call(xAxis);
return svg.node();
}
Insert cell
tooltip = d3
.select('body')
.append('div')
.style('position', 'absolute')
.style('z-index', '10')
.style('visibility', 'hidden')
.style('padding', '10px')
.style('background', 'rgba(0,0,0,0.6)')
.style('border-radius', '4px')
.style('color', '#fff');
Insert cell
x = d3
.scaleBand()
.domain(data.map((it) => it.name))
.range([0, graphWidth])
.paddingInner(0.2)
.paddingOuter(0.2);
Insert cell
y = d3
.scaleLinear()
.domain([0, maxPrice])
.range([graphHeight, 0]);
Insert cell
yAxis = d3.axisLeft(y);
Insert cell
xAxis = d3.axisBottom(x);
Insert cell
maxPrice = d3.max(data, (d) => d.price);
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
graphMarginLeft = (svgHeight - graphHeight) / 2
Insert cell
graphMarginTop = (svgWidth - graphWidth) / 2
Insert cell
d3 = require("d3@^6.2")
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