拿到的需求是实现自定义x、y、size、color的气泡图,color按值以色阶排布(提需求的是我女朋友,咱也不敢问,还得加班干你说气人不~),分析完需求后我决定学习下echarts的实现,代码如下:
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>KEGG</title>
<style>
body {
padding: 0px;
margin: 0px;
border: 0px;
}
</style>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="echarts.min.js"></script>
<script type="text/javascript" src="myScript.js"></script>
</head>
<body>
<div style="width:95%;margin:20px auto;">
<div style="width:95%;margin:0px 0px 50px 0px;" align="center">
<input type="file" id="dataFile">
<button type="button" onclick="getData()">生成图表</button>
</div>
<div id="chartDiv" style="width:95%;height:600px;"></div>
</div>
</body>
</html>
js:
function getData() {
var data = new Array();
var file = $("#dataFile")[0].files[0];
var reader = new FileReader();
reader.onload = function() {
var row = this.result.split("\r\n");
for(var i in row) {
if(i!=0) {
data[i-1] = new Array();
var cell = row[i].split(",");
for(var j in cell) {
data[i-1][j] = cell[j];
}
}
}
initChart(data);
}
reader.readAsText(file);
}
function initChart(data) {
var color = new Array();
for(var i in data) {
color[i] = data[i][3];
}
var max = Math.max.apply(null,color);
var min = Math.min.apply(null,color);
var myChart = echarts.init(document.getElementById('chartDiv'));
var option = {
title: {
text: 'KEGG',
x: 'center'
},
tooltip: {
formatter: function(params) {
return params.value[1]+" :<br>"+params.value[0];
}
},
dataRange: {
x: 'right',
y: 'center',
min: min,
max: max,
color:['red','blue'],
calculable: true,
formatter: function(value) {
return value;
}
},
xAxis: {
type: 'value'
},
yAxis: {
type: 'category'
},
series: [{
name: 'KEGG',
type: 'scatter',
symbolSize: function(value) {
return value[2]/5;
},
data: data
}]
};
myChart.setOption(option);
}
效果图:
这里的色阶排布我本来是自己写的算法来实现的,然后在series自定义显示,后来觉得echarts的dataRange或visualMap挺好用,就改了。
自定义色阶显示:
itemStyle: {
normal: {
color: function(params) {
return getColor(min,max,params.value[4]);
}
}
}
function getColor(min,max,n) {
var a = (n*255)/(max-min);
var r = 0;
var g = 0;
var b = 0;
if(n==min) {
b = 255;
} else if(n==max) {
r = 255;
} else {
b = 255-a;
r = a;
}
r = parseInt(r);
g = parseInt(g);
b = parseInt(b);
return rgbaToHex("rgb("+r+","+g+","+b+")");
}
function rgbaToHex(color) {
var values = color.replace(/rgba?\(/,'').replace(/\)/,'').replace(/[\s+]/g,'').split(',');
var a = parseFloat(values[3]||1);
var r = Math.floor(a*parseInt(values[0])+(1-a)*255);
var g = Math.floor(a*parseInt(values[1])+(1-a)*255);
var b = Math.floor(a*parseInt(values[2])+(1-a)*255);
return "#"+("0"+r.toString(16)).slice(-2)+("0"+g.toString(16)).slice(-2)+("0"+b.toString(16)).slice(-2);
}