效果图:(PS:双柱+双折线居中)
1.安装echarts
npm install echarts --save-dev
2.引入(也可按需引入)
import * as echarts from 'echarts';
3.html
<div id="mainBottom" className="mainBottom"></div>
4.js
var chartDom = document.getElementById('mainBottom');
//react项目 使用getElementsByClassName获取DOM会报错 TypeError: this.dom.getContext is not a function
var myChart = echarts.init(chartDom);
var option;
option = {
title: {
text: 'xxx',
textStyle:{ //---主标题内容样式
color: '#fff',
},
left: 'center',//居中
padding:[30,0]
},
tooltip: {
trigger: 'axis',
},
legend: {
},
grid: {
},
toolbox: {
show: true,
},
calculable: true,
xAxis: [
{
type: 'category',
data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
splitLine: { show: false }, //去除网格线
splitArea: { show: false }, //保留网格区域
axisTick: { show: false },//隐藏刻度线
axisLine: {
lineStyle: {
color: '#fff',//坐标值得具体的颜色
}
}
},
],
yAxis: [
{
axisLine: {
show: true, lineStyle: {
color: "#FFFFFF"
}
}, //y轴竖线
axisTick: { show: false },//y轴刻度
splitLine: { show: false, }, //y轴横线
type: 'value',
axisLabel: {
formatter: '{value} '
}
},
],
series: [
{
type: 'bar',
data: [2, 1, 1, 1, 1, 1, 2, 1, 3],
barGap: '0%',//中间不间隔
// barWidth: 80, //设置宽度
lineStyle: {
color: "#497FE7"//柱状图颜色
},
},
{
type: 'bar',
data: [5, 3, 4, 2, 1, 2, 1, 2, 3,8,9,1],
barGap: '0%',
itemStyle: {
color: "#56E5FE"//柱状图颜色
},
},
{
type: 'line',
xAxisIndex: 1,//表示使用xAxis下标为1的刻度线,如果超出xAxis的长度会报错
data: [2, 1, 1, 1, 1, 1, 2, 1, 3],
lineStyle: {
color: "#497FE7"
},
symbol: 'none',//去掉折线图的折点
},
{
type: 'line',
xAxisIndex: 1,
data: [5, 3, 4, 2, 1, 2, 1, 2, 3,8,9,1],
lineStyle: {
color: "#56E5FE"
},
symbol: 'none',
},
],
};
//添加一个新的刻度线 实现折线在柱状图的中间显示
option.xAxis[1] = {
type: 'value',
max: option.xAxis[0].data.length,
show: false
}
option.series[2].data = option.series[2].data.map((x, i) => [(0.25+i) , x])
option.series[3].data = option.series[3].data.map((x, i) => [(0.75+ i) , x])
//0.25和0.75表示两个折线图只需要向左向右偏移0.5即可实现居中(根据横坐标去计算)
myChart.setOption(option);