实现方法: 2个叠加,自定义Y轴方法
代码如下:
<template>
<div>
<div id="main" style="width:1200px;height:600px;"></div>
</div>
</template>
<script>
import echarts from "echarts";
const MAX = 50;
const data = [12, 33, 22, 7];
export default {
name: "echartssimple",
data() {
return {};
},
methods: {
init() {
this.myChart = echarts.init(document.getElementById("main"));
let option = {
backgroundColor: "rgba(0,0,0,0.1)",
grid: {
// 坐标轴的坐标
left: "15%",
right: "20%",
top: "15%"
},
xAxis: [
{
type: "category",
splitLine: {
show: false //垂直分割线
},
data: ["周一", "周二", "周三", "周四"]
},
{
type: "category",
axisLine: {
show: false
},
axisTick: {
show: false
},
axisLabel: {
show: false
},
splitArea: {
show: false
},
splitLine: {
show: false
},
data: []
}
],
yAxis: [
{
// name: "Y轴单位写的位置",
type: "value",
max: MAX,
splitLine: {
show: false //水平的分割线
},
axisLine: {
lineStyle: {
color: "transparent" //更改坐标轴颜色
}
},
axisLabel: {
show: true,
textStyle: {
color: "#000", //更改坐标轴文字颜色
fontSize: 16 //更改坐标轴文字大小
},
// 自定义的Y轴
formatter: function(value) {
var txs = [];
if (value == 0) {
txs.push("流量(MB)");
} else if (value == MAX) {
txs.push("社区数");
}
return txs;
}
}
}
],
series: [
{
type: "bar",
xAxisIndex: 1, // 柱状图
itemStyle: {
normal: {
// color: "rgba(0,0,0,0.2)" // 柱子的颜色
color: "transparent" // 柱子的颜色
}
},
label: {
// 柱子上面的颜色 大小等属性
normal: {
show: true,
fontSize: 16,
color: "#000",
position: "top",
formatter: "{c}",
formatter: function(params) {
var stuNum = 0;
data.forEach(function(value, index, array) {
if (params.dataIndex == index) {
stuNum = value;
}
});
return stuNum;
}
}
},
barWidth: "30", // 柱子宽度
data: [MAX, MAX, MAX, MAX]
},
{
type: "bar",
barWidth: "30",
data: data,
itemStyle: {
normal: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: "#91e3f7" },
{ offset: 1, color: "#468cff" }
])
}
}
}
]
};
// 使用刚指定的配置项和数据显示图表。
this.myChart.setOption(option);
}
},
mounted() {
this.init();
}
};
</script>
<style scoped>
</style>
ps: 如何让 社区数 和 数字在同一条水平线?
本文计算的MAX的方式,是基于data的最大值基础上再进行增加一个增量A(目的是最大值的柱子不会在顶到顶部,大概80%的位置,为了美观),然后 data: [MAX-A, MAX–A, MAX–A, MAX–A],结束了。