HTML
1 |
<div id="main"></div> |
CSS
1 2 3 4 |
#main { width: 100%; height: 500px; } |
JS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
// 初始化图表实例 var myChart = echarts.init(document.getElementById("main")); var xAxisData = []; var data1 = new Array(3).fill(3); var data2 = new Array(3).fill(4); var totalData = []; for (var i = 0; i < data1.length; i++) { xAxisData.push("class" + i); totalData.push(data1[i] + data2[i]); } var option = { legend: { data: ["bar1", "bar2"], left: "center", bottom: 0 }, tooltip: { trigger: "axis", axisPointer: { type: "shadow" } }, xAxis: { data: xAxisData, name: "X Axis" }, yAxis: {}, grid: { bottom: "10%", right: "10%", left: "10%" }, series: [ { name: "bar1", type: "bar", stack: "total", barWidth: "20%", label: { show: true }, data: data1 }, { name: "bar2", type: "bar", stack: "total", barWidth: "20%", label: { show: true }, data: data2 }, { name: "总数", type: "bar", barWidth: "20%", barGap: "-100%", // 左移100%,stack不再与上面两个在一列 label: { normal: { show: true, position: "top", // 位置设为top formatter: "{c}", textStyle: { color: "#000" }, formatter: (params) => { return data1[params.dataIndex] + data2[params.dataIndex]; } } }, itemStyle: { normal: { color: "rgba(128, 128, 128, 0.1)" // 仍为透明 } }, data: totalData } ] }; // 使用配置项生成图表 myChart.setOption(option); window.addEventListener("resize", function () { myChart.resize(); }); |