eCharts 的 bar 系列

eCharts bar 系列的配置

在整个过程中踩了很多的坑,不知道是什么原因,barWidth 设置的宽度过大时会使得两个重叠的 bar 系列的宽度不相同,如若有人发现问题所在,欢迎指正。

html中引入指令

1
<div data-e-charts data-config="identityData" style="height:200px"></div>

directive.js 参见官网配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
angular.module('myApp')
.directive('eCharts', ['app', '$rootScope', function (app, $rootScope) {
...
bar: {
grid: {
top: 12,
left: 16,
right: '-12%',
bottom: 0,
containLabel: true
},
yAxis: {
data: []
},
series: [],
init: function () {
this.yAxis.data = [];
var sum = 0, i, j;
for (i = 0; i < this.data.length; i++) {
this.yAxis.data.push(this.data[i].name);
sum += this.data[i].value;
}
// 背景系列 bar
this.series[0] = {};
this.series[0].type = 'bar';
this.series[0].itemStyle = {normal: {color: 'grey'}, emphasis: {color: 'grey'}};
this.series[0].silent = true;
this.series[0].barWidth = 18;
this.series[0].barGap = '-100%';
this.series[0].data = [];
for (j = 0; j < this.data.length; j++) {
this.series[0].data.push(sum);
}
// 实际数据 bar
this.series[1] = {};
this.series[1].type = 'bar';
this.series[1].barWidth = 18;
this.series[1].z = 5;
this.series[1].data = this.data;
for (j = 0; j < this.color.length; j++) {
// 每条 bar 的颜色
this.series[1].data[j].itemStyle = {
normal: {color: this.color[j]},
emphasis: {color: this.color[j]}
};
this.series[1].label = {
normal: {
show: true,
position: 'right',
offset: [5, -2],
formatter: function (p) {
var ratio = Math.round(p.value / sum * 100);
return p.value + ' ( ' + ratio + '%' + ' ) ';
}
},
emphasis: {}
};
}
...
}
}
return {
scope: {config: '='},
link: function (scope, element) {
...
}
};
}]);

controller.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$scope.identityData = {
type: 'bar',
data: [],
color: ['red', 'orange', 'green', 'green']
};
// 获取数据
$scope.getIdentityData = function () {
$http({
url:'/test/testData/identity',
method:'GET'
}).success(function(data, header, config, status) {
//响应成功
$scope.identityData = data;
}).error(function(err) {
//处理响应失败
console.log(err);
});
};

data.js

1
2
3
4
5
6
7
8
module.exports = {
identity: [
{name: '我爱你', value: 12},
{name: '我爱他', value: 34},
{name: '他爱你', value: 79},
{name: '你爱他', value: 23}
]
}
感谢您的支持!