使用echarts-stat包做echart散点图的线性回归,渲染后显示的公式只保留了两位小数, 请问一下可以设置公式的保留小数点后多几位吗
以通过 echarts-stat 包中的 regression 函数的第三个参数来设置回归方程的保留小数位数。具体实现方法如下:
// 导入 echarts 和 echarts-stat 包
import echarts from 'echarts';
import { regression } from 'echarts-stat';
// 构造数据
const data = [[1, 1], [2, 3], [3, 7], [4, 13], [5, 21]];
// 计算回归方程
const result = regression('linear', data, 1, { precision: 4 });
// 构造 echarts 图表配置
const option = {
xAxis: {
type: 'value'
},
yAxis: {
type: 'value'
},
series: [
{
name: 'scatter',
type: 'scatter',
data: data
},
{
name: 'line',
type: 'line',
data: result.points
},
{
name: 'regression',
type: 'text',
position: 'end',
silent: true,
itemStyle: { fontSize: 14 },
encode: { text: 2 },
data: [{ name: 'regression', value: `y=${result.parameter.gradient.toFixed(4)}x+${result.parameter.intercept.toFixed(4)}` }]
}
]
};
// 渲染 echarts 图表
const chart = echarts.init(document.getElementById('chart'));
chart.setOption(option);
在上述代码中,我们调用了 regression 函数来计算线性回归方程,并通过第四个参数 { precision: 4 } 来设置保留小数点后 4 位。然后,我们将回归方程作为 text 系列添加到 echarts 图表中,并将 encode 属性设置为 { text: 2 },以便将回归方程显示在数据点的右侧。最后,我们通过 toFixed 方法将回归系数和截距值保留小数点后 4 位,并将它们拼接成回归方程的字符串。