Label 图形文本
在每个几何标记 geom 上调用 label 方法,指定需要显示的数据维度即可:
- const data = [
- { genre: 'Sports', sold: 275 },
- { genre: 'Strategy', sold: 115 },
- { genre: 'Action', sold: 120 },
- { genre: 'Shooter', sold: 350 },
- { genre: 'Other', sold: 150 }
- ];
- const chart = new G2.Chart({
- container: 'c0',
- height: 300,
- forceFit: true,
- padding: [ 40, 20, 95, 80 ]
- });
- chart.source(data, {
- genre: {
- alias: '游戏种类' // 列定义,定义该属性显示的别名
- },
- sold: {
- alias: '销售量'
- }
- });
- chart.interval().position('genre*sold').color('genre').label('sold');
- chart.render();
更多配置项请查看 label api。
完整代码如下:
- const data = [
- { name: 'Microsoft Internet Explorer', value: 56.33 },
- { name: 'Chrome', value: 24.03 },
- { name: 'Firefox', value: 10.38 },
- { name: 'Safari', value: 4.77 },
- { name: 'Opera', value: 0.91 },
- { name: 'Proprietary or Undetectable', value: 0.2 }
- ];
- const dv = new DataSet.DataView();
- dv.source(data).transform({
- type: 'percent',
- dimension: 'name',
- as: 'percent'
- });
- const chart = new G2.Chart({
- container: 'c1',
- width: 800,
- height: 400
- });
- chart.source(dv);
- // 重要:绘制饼图时,必须声明 theta 坐标系
- chart.coord('theta', {
- radius: 0.8 // 设置饼图的大小
- });
- chart.tooltip({
- showTitle: false
- });
- chart.intervalStack()
- .position('percent')
- .color('name')
- .tooltip('name*percent', (name, percent) => {
- return {
- name,
- value: (percent * 100).toFixed(2) + '%'
- };
- })
- .label('name', {
- formatter: (text, item, index) => {
- const point = item.point; // 每个弧度对应的点
- let percent = point['percent'];
- percent = (percent * 100).toFixed(2) + '%';
- return text + ' ' + percent;
- }
- });
- chart.render();
label 除了可以格式化文本的显示,也支持使用 html 自定义显示的样式。只需要定义 htmlTemplate 格式化文本的回调函数即可,如下例所示:
- const data = [
- { name: '示例 A', value: 38.8 },
- { name: '示例 B', value: 9.15 },
- { name: '示例 C', value: 26.35 },
- { name: '示例 D ', value: 22.6 },
- ];
- const dv = new DataSet.DataView();
- dv.source(data).transform({
- type: 'percent',
- field: 'value',
- dimension: 'name',
- as: 'percent'
- });
- const chart = new G2.Chart({
- container: 'c2',
- width: 800,
- height: 400
- });
- chart.source(dv);
- // 重要:绘制饼图时,必须声明 theta 坐标系
- chart.coord('theta', {
- radius: 0.8 // 设置饼图的大小
- });
- chart.tooltip({
- showTitle: false
- });
- chart.intervalStack()
- .position('percent')
- .color('name')
- .tooltip('name*percent', (name, percent) => {
- return {
- name: name,
- value: (percent * 100).toFixed(2) + '%'
- };
- })
- .label('name', {
- labelLine: false, // 不显示文本的连接线
- offset: 30, // 文本距离图形的距离
- htmlTemplate: (text, item, index) => {
- const point = item.point; // 每个弧度对应的点
- let percent = point['percent'];
- percent = (percent * 100).toFixed(2) + '%';
- return '<span class="title" style="display: inline-block;width: 50px;">' + text + '</span><br><span style="color:' + point.color + '">' + percent + '</span>'; // 自定义 html 模板
- }
- chart.render();