根据项目需求柱状图始终显示24小时的数据,跨天后两天的数据用不同的颜色表示。
主要是对图表里 series.itemStyle的color的设置。
完整源码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>根据横坐标显示不同颜色</title>
<style>
.main {
width: 856px;
height: 640px;
/* background-color: lightskyblue; */
border: 1px solid #ccc;
margin: 110px auto 0 auto;
}
</style>
</head>
<body>
<!-- 放置图标 -->
<div id="main" class="main"></div>
<!-- 引入相关文件 -->
<script src="js/jquery-2.1.4.min.js"></script>
<!-- 引入 ECharts 文件 -->
<script src="js/echarts.js"></script>
<script>
// 基于准备好的dom,初始化echarts实例
var echart = echarts.init(document.getElementById('main'));
var datax = ['2019-10-17 21:00','2019-10-17 22:00','2019-10-17 23:00','2019-10-18 00:00', '2019-10-18 01:00', '2019-10-18 02:00', '2019-10-18 03:00', '2019-10-18 04:00', '2019-10-18 05:00', '2019-10-18 06:00',
'2019-10-18 07:00', '2019-10-18 08:00', '2019-10-18 09:00', '2019-10-18 10:00:00', '2019-10-18 11:00', '2019-10-18 12:00', '2019-10-18 13:00', '2019-10-18 14:00', '2019-10-18 15:00', '2019-10-18 16:00', '2019-10-18 17:00',
'2019-10-18 18:00', '2019-10-18 19:00', '2019-10-18 20:00']
var datas= ['92', '72', '80', '92', '60', '89', '82', '68', '98', '86', '79', '84', '76', '87', '62', '72', '82', '98', '86', '79', '87', '74', '82', '62']
// 指定相关的配置项和数据
var option = {
title: {
text: '柱状图'
},
//鼠标滑过展示数据
tooltip: {
show: true,
trigger: 'item',
backgroundColor: 'rgba(0,0,0,.3)',
textStyle: {
color: 'rgb(255,255,255)',
},
formatter: '{b}<br>{c}'
},
color: ['#289df5',''],
grid: {
top: '15%',
left: '24',
right: '6%',
bottom: '15',
containLabel: true
},
// X轴样式
xAxis: {
type: 'category',
axisLine: {
show: false
},
axisTick: {
length: 0 // 刻度线的长度
},
axisLabel: {
interval: 0, // 坐标轴刻度标签的显示间隔,在类目轴中有效。
textStyle: {
color: '#00c5d7'
},
show: true,
textStyle: {
fontSize: 12
},
formatter: function (value, index) {
// 格式化成月/日,只在第一个刻度显示年份
var date = new Date(value)
return (date.getHours()) + '时'
}
},
name: '(时)',
nameTextStyle: {
padding: [24, 0, 0, 0],
color: '#00c5d7'
},
nameGap: 0,
data: datax,
axisTick: {
alignWithLabel: true
}
},
yAxis: {
type: 'value',
axisLine: {
show: false
},
axisTick: {
length: 0 // 刻度线的长度
},
splitLine: {
lineStyle: {
// color: ["#051d5f"],
color: ['#094386'],
width: 1,
type: 'solid'
}
},
axisLabel: {
textStyle: {
color: '#a3a4b2'
}
}
},
series: [{
name: ' ',
type: 'bar',
smooth: false,
itemStyle : {
normal : {
//color:'#8cd5c2', //改变柱子的颜色
color: function(params){
var date = new Date(datax[params.dataIndex])
var curHours = (date.getHours())
var maxDate = new Date((datax[datax.length - 1]))
var maxHours = (maxDate.getHours())
if (parseInt(curHours) >= 1 && parseInt(curHours) <= parseInt(maxHours)) {
return '#fbc01b'
}else{
return '#289df5'
}
}
}
},
data: datas,
}],
};
echart.setOption(option);
// echart图表自适应
window.addEventListener("resize", function() {
echart.resize();
});
</script>
</body>
</html>