1.示例图

2.实现
先写一个柱状图,然后在每个柱状图上加一条横线,最后在统一实现柱状图的渐变背景
<template>
<div class="abnormal-sg">
<div
ref="discountChart"
class="chart-box__canvas"
/>
</div>
</template>
<script>
import * as echarts from 'echarts'
export default {
name: 'Abnormal',
data () {
return {
chartInstance: null,
xData: ['苹果', '香蕉', '橙子'],
yData: [20, 100, 50]
}
},
mounted () {
this.initChart()
// 图表自适应
window.addEventListener('resize', this.handleResize)
},
beforeDestroy () {
window.removeEventListener('resize', this.handleResize)
if (this.chartInstance) {
this.chartInstance.dispose()
this.chartInstance = null
}
},
methods: {
initChart () {
this.initDiscountChart(this.$refs.discountChart)
},
handleResize () {
if (this.chartInstance) {
this.chartInstance.resize()
}
},
// 初始化图表
initDiscountChart (el) {
if (!el) return null
if (this.chartInstance) {
this.chartInstance.dispose()
}
const chart = echarts.init(el)
this.chartInstance = chart
chart.setOption({
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'line',
lineStyle: {
type: 'dashed' // dashed虚线 solid实线 dotted点线
}
}
},
grid: {
left: 60,
right: 20,
bottom: 30,
top: 40
},
xAxis: {
type: 'category',
data: this.xData,
axisLabel: {
fontSize: 16
},
axisLine: {
show: false
},
axisTick: {
show: false
}
},
yAxis: {
type: 'value',
name: '单位:个',
nameTextStyle: {
fontSize: 16
},
splitLine: {
lineStyle: {
color: '#e2e8f6',
type: 'dashed'
}
},
axisLine: {
show: false
},
axisTick: {
show: false
},
axisLabel: {
fontSize: 16
}
},
series: [
{
type: 'bar',
barWidth: '100%',
barCategoryGap: '0%',
stack: 'topLineStack',
data: this.yData,
itemStyle: {
color: '#c2e0fe'
}
},
// ----------------------横线----------------------------
{
type: 'custom',
coordinateSystem: 'cartesian2d',
data: this.yData.map((value, index) => [
this.xData[index],
value
]),
renderItem: (params, api) => {
const x = api.coord([api.value(0), api.value(1)])[0]
const y = api.coord([api.value(0), api.value(1)])[1]
// 获取当前分类的宽度
const bandWidth = api.size([1, 0])[0]
// 横线宽度为分类宽度
return {
type: 'line',
shape: {
x1: x - bandWidth / 2,
y1: y,
x2: x + bandWidth / 2,
y2: y
},
style: {
stroke: 'green',
lineWidth: 2
},
silent: true
}
},
silent: true,
tooltip: {
show: false
},
z: 10
}
]
})
// -----------------------渐变颜色-------------------------
// 获取实际绘图区的位置和高度
const gridRect = chart
.getModel()
.getComponent('grid')
.coordinateSystem
.getRect()
// 创建整个绘图区共用的垂直渐变
const gradient = new echarts.graphic.LinearGradient(
0,
gridRect.y,
0,
gridRect.y + gridRect.height,
[
{
offset: 0,
color: 'rgba(103, 194, 58, 0.8)'
},
{
offset: 1,
color: 'rgba(230, 241, 255, 0.7)'
}
],
true
)
// 应用统一渐变
chart.setOption({
series: [
{
itemStyle: {
color: gradient
}
}
]
})
return chart
}
}
}
</script>
<style scoped lang="scss">
.abnormal-sg {
width: 100%;
height: 200px;
}
.chart-box__canvas {
width: 100%;
height: 100%;
}
</style>
一般图表可参考:echarts图表集