最近项目有这样一个需求,需要在echarts图下生成一个表格 效果图:
代码,直接复制粘贴到echarts官网编辑器里面即可:
const xData = [
{
name: "销售单价",
list: [
13780.1, 15620.3, 15562.6, 16520.2, 17563.2, 18620.7, 19623.5, 20520.9,
21530.6, 22025.7, 23520.7, 1000,
],
},
{
name: "销售量",
list: [
137850.1, 145620.3, 154562.6, 165230.2, 175623.2, 185620.7, 196523.5,
201520.9, 215230.6, 220325.7, 236520.7, 10000,
],
},
];
const xArr = [
"1月",
"2月",
"3月",
"4月",
"5月",
"6月",
"7月",
"8月",
"9月",
"10月",
"11月",
"12月",
];
const getXTable = (data) => {
return data.map((item, idx) => {
return {
position: "bottom", // 将分组x轴位置定至底部,不然默认在顶部
offset: 60 + idx * 30, // 向下偏移,使分组文字显示位置不与原x轴重叠
max: xArr.length - 1,
axisTick: {
length: 0, // 延长刻度线做分组线
inside: true, // 使刻度线相对轴线在上面与原x轴相接,默认在轴线下方
lineStyle: { color: "#000" }, // 非必须,仅为了演示,明显标示出分组刻度线
},
axisLabel: {
inside: true, // 使刻度名称相对轴线在上面与原x轴相接,默认在轴线下方
interval: 0, // 强制显示全部刻度名
},
data: item.list,
};
});
};
const getSeries = (data) => {
return data.map((item) => {
return {
name: item.name,
type: "bar",
data: item.list,
};
});
};
const getGrid = () => {
const length = xData.length;
return {
x: 100,
y2: 75 + 30 * length,
};
};
option = {
grid: getGrid(),
tooltip: {
trigger: "axis",
axisPointer: {
type: "cross",
crossStyle: {
color: "#999",
},
},
},
toolbox: {
feature: {
dataView: { show: true, readOnly: false },
magicType: { show: true, type: ["bar"] },
restore: { show: true },
saveAsImage: { show: true },
},
},
legend: {
data: xData.map((item) => item.name),
},
xAxis: [
{
type: "category",
max: xArr.length - 1,
axisLabel: {
fontWeight: "bold",
show: true,
textStyle: {
fontSize: "14px",
},
},
axisPointer: {
type: "shadow",
},
data: xArr,
},
{
position: "bottom", // 将分组x轴位置定至底部,不然默认在顶部
offset: 0, // 向下偏移,使分组文字显示位置不与原x轴重叠
axisTick: {
length: -(xData.length + 1) * 30, // 延长刻度线做分组线
inside: true, // 使刻度线相对轴线在上面与原x轴相接,默认在轴线下方
lineStyle: { color: "#000" }, // 非必须,仅为了演示,明显标示出分组刻度线
},
max: xArr.length - 1,
axisLabel: {
inside: true, // 使刻度名称相对轴线在上面与原x轴相接,默认在轴线下方
interval: 0, // 强制显示全部刻度名
},
data: [""],
},
{
position: "bottom", // 将分组x轴位置定至底部,不然默认在顶部
offset: 30, // 向下偏移,使分组文字显示位置不与原x轴重叠
axisTick: {
length: 0, // 延长刻度线做分组线
inside: true, // 使刻度线相对轴线在上面与原x轴相接,默认在轴线下方
lineStyle: { color: "#000" }, // 非必须,仅为了演示,明显标示出分组刻度线
},
axisLabel: {
inside: true, // 使刻度名称相对轴线在上面与原x轴相接,默认在轴线下方
interval: 0, // 强制显示全部刻度名
},
},
...getXTable(xData),
],
yAxis: [
{
type: "value",
name: "数量:吨",
axisLabel: {
textStyle: {
fontSize: "14px",
},
},
},
],
series: getSeries(xData),
};
至于和legend联动,可以通过echarts的legend事件筛选数据,也有其他的方法,具体看各位需求场景。