Public
Edited
Nov 29, 2023
Insert cell
Insert cell
{
const CELL_HEIGHT = 30; // 每一行的高度
const PADDING = 5; // 边距
const MAX_ROWS = 20; // 最多的数据条数,不包过表头那一行
const HEIGHT = CELL_HEIGHT * (MAX_ROWS + 1) + PADDING * 2; // 计算最大的高度

const chart = new G2.Chart({
theme: "classic",
padding: PADDING,
height: HEIGHT // 固定图表的最大高度,如果超出会被截取,如果不够会留白
});

chart.options({
type: Table,
data: {
type: "fetch",
value: "https://assets.antv.antgroup.com/s2/basic-table-mode.json"
},
cell: {
// 表格的样式
height: 30,
stroke: "#e6e9f5",
strokeWidth: 1,
fontSize: 12
},
text: {
// 文本的样式
textAlign: "center",
textBaseline: "middle",
fontSize: 12
}
});

await chart.render();

return chart.getContainer();
}
Insert cell
function Table(options, dimensions) {
const { data, cell = { height: 30 }, text = {} } = options;
const keys = Array.from(new Set(data.flatMap(Object.keys)));
const table = [keys, ...data.map((d) => keys.map((key) => d[key]))];
const cells = table.flatMap((row, y) =>
row.map((col, x) => ({ key: col, x, y }))
);
const { height } = dimensions;
const rows = data.length + 1;
const expectedHeight = cell.height * rows;
const range = expectedHeight / height;
return [
{
type: "cell",
data: cells,
encode: {
x: "x",
y: "y"
},
scale: {
y: { range: [0, range] }
},
axis: false,
style: {
fill: (d) =>
d.y === 0 ? "#e1eafd" : d.y % 2 === 1 ? "#f6f8fe" : "#ffffff",
...cell
},
tooltip: false,
animate: false
},
{
type: "text",
data: cells,
encode: {
x: "x",
y: "y",
text: "key"
},
style: {
fontWeight: (d) => (d.y === 0 ? "bold" : undefined),
...text
},
tooltip: false,
animate: false
}
];
}
Insert cell
G2 = require("@antv/g2/dist/g2.min.js")
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