echarts官网: https://echarts.apache.org/zh/index.html
option = {
xAxis: {},
yAxis: {},
series: [
{
symbolSize: 20,
data: [
[10.0, 8.04],
[8.07, 6.95],
[13.0, 7.58],
[9.05, 8.81],
[11.0, 8.33],
[14.0, 7.66],
[13.4, 6.81],
[10.0, 6.33],
[14.0, 8.96],
[12.5, 6.82],
[9.15, 7.2],
[11.5, 7.2],
[3.03, 4.23],
[12.2, 7.83],
[2.02, 4.47],
[1.05, 3.33],
[4.05, 4.96],
[6.03, 7.24],
[12.0, 6.26],
[12.0, 8.84],
[7.08, 5.82],
[5.02, 5.68]
],
type: 'scatter'
}
]
}
上述是官网给出的散点图代码示例,data需要传入一个二维数组,我的问题就出现在传值这里。我后端传过来一个double类型的二维数组,但是在赋值这里出现了问题。由于直接从后端传过来的是一个object对象,因此不可以直接赋值给data,否则就会在前端报错,显示数据类型不匹配等等。
这里的做法应该是进行一个for循环,将传过来的数组中的数值拿出来。
注意不要直接option.series.data=res.data[i]这样赋值 ,会出现属性不匹配的问题
下面放上正确的代码:
是用vue写的
<template>
<div>
<el-card>
<!-- 散点图-->
<div id="point" style="height: 900px;width: 1800px"></div>
</el-card>
</div>
</template>
var option = {
xAxis: {
scale: true,
type:'value'
},
yAxis: {
scale: true,
type:'value'
},
series: [
{
symbolSize: 20,
data: this.points,
type: 'scatter'
}
]
};
var PointDom = document.getElementById('point');
var pointChart = echarts.init(PointDom);
this.request.get("/echarts/point").then(res =>{
if(res.code==='200'){
for (let i = 0; i < res.data.length; i++) {
var zero=res.data[i][0];
var one=res.data[i][1];
var newArr=[zero,one]
this.points.push(newArr)
}
}
pointChart.setOption(option);
})
@GetMapping("/point")
public Result pointGraph(){
double[][] doubles = autoReplace("D:\\桌面\\Dataset.pl.t001_43.r052.p2m");
return Result.success(doubles);
}
private static double[][] autoReplace(String filePath) {
File file = new File(filePath);
Long fileLength = file.length();
byte[] fileContext = new byte[fileLength.intValue()];
FileInputStream in = null;
try {
in = new FileInputStream(filePath);
in.read(fileContext);
// 避免出现中文乱码,和换行问题
String str = new String(fileContext, "utf-8");
String strArray[]=str.split("\r\n");
double[][] number=new double[strArray.length-3][2];
for (int i=3;i<strArray.length;i++){
String[] split = strArray[i].split(" ");
// System.out.println(split[4]);
// System.out.println(split[5]);
number[i-3][0]=Double.parseDouble(split[4]);
number[i-3][1]=Double.parseDouble(split[5]);
}
return number;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return new double[0][];
}
后端是从文件中读取出一个二维数组出来给前端。