Echarts使用dataTool写可自定义横坐标的盒须图(箱线图)
import dataTool from "echarts/extension/dataTool";
export default {
name: "BoxplotChart",
props: {
boxplotData: {
type: Object,
required: true,
},
},
data() {
return {
option: {
title: {
text: "",
left: 10, //标题显示的位置
},
tooltip: {
trigger: "item",
axisPointer: {
type: "cross",
},
},
grid: {
left: "10%",
right: "10%",
bottom: "15%",
},
xAxis: {
data: [],
type: "category",
boundaryGap: true,
nameGap: 30,
splitArea: {
show: false,
},
splitLine: {
show: false,
},
},
yAxis: {
type: "value",
name: "",
splitArea: {
show: true,
},
},
series: [
{
name: "非异常值",
type: "boxplot",
data: [],
tooltip: {
//以下是设置tooltip的显示数据和显示格式
formatter: function (param) {
return [
" " + param.name + ": ",
"上限: " + param.data[5],
"上四分位数: " + param.data[4],
"中位数: " + param.data[3],
"下四分位数: " + param.data[2],
"下限: " + param.data[1],
].join("<br/>");
},
},
},
{
name: "异常值",
type: "scatter",
data: [],
},
],
},
};
},
mounted() {
this.initChart();
},
watch: {
boxplotData: function (newVal, oldVal) {
this.initChart();
},
},
methods: {
initChart() {
//使用echarts的dataTool准备数据
let dataTmp = this.$echarts.dataTool.prepareBoxplotData(
this.boxplotData.boxData
);
//设置option
//设置非异常值数据
this.option.series[0].data = dataTmp.boxData;
//设置异常值数据
this.option.series[1].data = dataTmp.outliers;
//根据传入的boxplotData数据动态设置
//设置盒须图标题
this.option.title.text = this.boxplotData.title;
//设置横坐标
this.option.xAxis.data = this.boxplotData.xAxisData;
//设置纵坐标
this.option.yAxis.name = this.boxplotData.yAxisName;
const myChart = this.$echarts.init(this.$refs.BoxPlotChart);
// 监听窗体大小变化实现自适应
window.addEventListener("resize", function () {
myChart.resize();
});
myChart.setOption(this.option);
},
},
};