Published
Edited
Mar 15, 2021
Insert cell
Insert cell
Insert cell
G = require('@antv/g-canvas')
Insert cell
{
// 创建容器
const container = html`<div></div>`;
// 创建 g-canvas
const canvas = new G.Canvas({
container,
width,
height,
});
// 创建用于承载 shape 的 group
const group = canvas.addGroup();
// 计算柱子的宽度
const barWidth = Math.floor((width - margin.left - margin.right) / data.length) / 2;
const gap = barWidth;
// 计算柱子的高度
const dataMax = Math.max(...data.map(datum => datum.percent));
const barHeight = (value) => {
return (height - margin.top - margin.bottom) * (value / dataMax);
}
// 将数值信息转换为 x 轴坐标信息的映射函数
const xScale = (i) => {
return (barWidth + gap) * i + margin.top + barWidth / 2;
}
// 将数值信息转换为 y 轴坐标信息的映射函数
const yScale = (value) => {
return (height - margin.top - margin.bottom) - barHeight(value) + margin.top;
}
// 遍历数据
data.forEach((datum, index) => {
// 添加 shape
group.addShape('rect', {
attrs: {
x: xScale(index),
y: yScale(datum.percent),
width: barWidth,
height: barHeight(datum.percent),
fill: 'steelblue',
}
});
// 添加标签
group.addShape('text', {
attrs: {
x: xScale(index) + barWidth / 2,
y: yScale(datum.percent) - 5,
text: `${datum.percent}%`,
fill: '#333',
textAlign: 'center',
}
});
// 添加x轴刻度
group.addShape('line', {
attrs: {
x1: xScale(index) + barWidth / 2,
y1: height - margin.bottom + 1,
x2: xScale(index) + barWidth / 2,
y2: height - margin.bottom + 6,
stroke: '#333',
}
});
// 添加x轴标签
group.addShape('text', {
attrs: {
x: xScale(index) + barWidth / 2,
y: height - margin.bottom + 20,
text: datum.browser,
fill: '#333',
textAlign: 'center',
}
});
})
// 添加 y 轴标题
const yTitle = group.addShape('text', {
attrs: {
x: 10,
y: 10,
text: 'Percentage(%)',
fill: '#333',
}
});
// 添加x轴水平线
const xAxisLine = group.addShape('line', {
attrs: {
x1: margin.left,
y1: height - margin.bottom,
x2: width - margin.right,
y2: height - margin.bottom,
stroke: '#333',
}
});
// 添加 y 轴刻度及标签
const yLabels = [0, 10, 20, 30, 40, 50, 60];
yLabels.forEach(label => {
// 刻度
group.addShape('line', {
attrs: {
x1: margin.left - 5,
y1: yScale(label),
x2: margin.left - 10,
y2: yScale(label),
stroke: '#333',
}
});
// 标签
group.addShape('text', {
attrs: {
x: margin.left - 12,
y: yScale(label),
text: label,
fill: '#333',
textAlign: 'right',
textBaseline: 'middle',
}
});
})
return container;
}
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