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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
| // 递归的获取obj中的prop属性 解决有时需要取val.obj.prop的情况
| function getPropValueLoop(obj, prop) {
| if (typeof prop !== 'string') {
| return obj;
| }
| const props = prop.split('.');
| let result = obj;
| props.forEach((item) => {
| result = result[item];
| });
| return result;
| }
| function getCount(array, element) {
| let count = 0;
| array.forEach((e) => {
| if (e == element) {
| count++;
| }
| });
| return count;
| }
| export default {
| /** 将chart图表转化为图片url
| * @param chart: chart图表的实例
| * */
| chartToImageUrl(chart) {
| const dataURL = chart.getDataURL({
| pixelRatio: 5, // 提高图片质量
| backgroundColor: '#FFFFFF', // 设置背景颜色
| excludeComponents: ['toolbox'], // 排除工具箱组件
| type: 'png' // 输出图片类型为PNG
| });
| return dataURL;
| },
| // 展示 data 数组中对象的 prop 属性的饼图, title 是饼图的标题
| getPieChartByDataAndProp(data, prop, label) {
| let chartData = [];
| function hasThisName(name) {
| for (let index = 0; index < chartData.length; index++) {
| const element = chartData[index];
| if (element.name === name) {
| return true;
| }
| }
| return false;
| }
|
| data.map((item) => {
| const name = getPropValueLoop(item, prop);
| if (hasThisName(name)) {
| chartData.map((item) => {
| if (item.name === name) {
| item.value++;
| }
| });
| } else {
| chartData.push({
| name: name,
| value: 1
| });
| }
| });
|
| return {
| title: {
| text: label,
| left: 'center'
| },
| tooltip: {
| trigger: 'item'
| },
| legend: {
| orient: 'vertical',
| left: 'left'
| },
| series: [
| {
| type: 'pie',
| radius: '50%',
| data: chartData,
| emphasis: {
| itemStyle: {
| shadowBlur: 10,
| shadowOffsetX: 0,
| shadowColor: 'rgba(0, 0, 0, 0.5)'
| }
| }
| }
| ]
| };
| },
| // 展示 data 数组中对象的 prop 属性的直方图, title 是直方图的标题
| getBarChartByDataAndProp(data, prop, title) {
| let series = data.map((item) => getPropValueLoop(item, prop));
| const option = {
| title: {
| text: title //设置标题
| },
| xAxis: {
| type: 'category',
| data: Array.from(new Set(series)),
| axisLabel: {
| rotate: 45, // 旋转标签,避免重叠
| // 或者
| interval: 0 // 显示所有标签,可能导致重叠,根据需求调整
| }
| },
| yAxis: {
| type: 'value'
| },
| series: [
| {
| data: Array.from(new Set(series)).map((item) =>
| getCount(series, item)
| ),
| type: 'bar',
| smooth: true
| }
| ]
| };
| return option;
| }
| };
|
|