Published
Edited
Mar 15, 2021
Insert cell
Insert cell
Insert cell
d3 = require('d3@6')
Insert cell
{
const margin = ({top: 50, right: 50, bottom: 50, left: 50});
// y 度量
const y = d3.scaleLinear()
.domain([0, d3.max(data, d => d.percent)])
.range([height - margin.bottom, margin.top]);
// x 度量
const x = d3.scaleBand()
.domain(data.map(d => d.browser))
.rangeRound([margin.left, width - margin.right])
.padding(0.5);
// y 轴标题
const yTitle = g => g.append("text")
.attr("font-family", "sans-serif")
.attr("font-size", 12)
.attr("y", 10)
.text("Percentage(%)");
// y 坐标轴
const yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y))
.call(g => g.select(".domain").remove());
// x 坐标轴
const xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).tickSizeOuter(0));
// 创建 svg
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);
// 添加柱子
svg.append('g')
.attr('fill', 'steelblue')
.selectAll('rect')
.data(data)
.join('rect')
.attr('x', d => x(d.browser) )
.attr('y', d => y(d.percent))
.attr('height', d => y(0) - y(d.percent))
.attr('width', x.bandwidth());
// 添加标签
svg.append('g')
.selectAll('text')
.data(data)
.join('text')
.attr("font-family", "sans-serif")
.attr("font-size", 12)
.attr('text-anchor', 'middle')
.attr('x', d => x(d.browser) + x.bandwidth() / 2)
.attr('y', d => y(d.percent) - 5)
.text(d => `${d.percent}%`);
// 添加 x 轴
svg.append("g")
.call(xAxis)

// 添加 y 轴
svg.append("g")
.call(yAxis);
// 添加 y 轴标题
svg.call(yTitle);

return svg.node();
}
Insert cell
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