html
<body>
<div id="map" style="margin: 0 auto;width: 1200px;height:400px;border: 1px solid #ccc;"></div>
<script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
<script>
const myChart = echarts.init(document.getElementById('map'));
const typeColors = {
jian: { backgroundColor: '#F6C0C6', width: 40, height: 16 },
feng: { backgroundColor: '#F9E192', width: 40, height: 16 },
ping: { backgroundColor: '#CAD6F0', width: 40, height: 16 },
gu: { backgroundColor: '#E1F1D6', width: 40, height: 16 }
}
const typeMap = { "jian": '尖', "feng": '峰', "ping": '平', "gu": '谷' }
function generateRandomData() {
return Array.from({ length: 24 }, (_, index) => {
const type = ["jian", "feng", "ping", "gu"][Math.floor(Math.random() * 4)];
return {
value: Math.floor(Math.random() * 500 + 10),
value2: Math.floor(Math.random() * 500 + 10),
date: index + 1 + "时",
type: type,
color: typeColors[type]
};
});
}
const data = generateRandomData()
const xAxisData = data.map(item => item.date)
const seriesData = data.map(item => item.value)
const seriesData2 = data.map(item => item.value2)
const option = {
tooltip: {
trigger: 'axis',
formatter: function (params) {
const index = params[0].dataIndex
const type = data[index].type;
const date = data[index].date;
return typeMap[type] + date + '<br>' + params.map((item, index) => {
return `${item.marker} ${['工作日', '节假日'][index]} ${item.value} kWh`
}).join("<br>")
}
},
legend: {
top: '10', // 图例显示在顶部
left: '10', // 图例水平居中
},
color: ['#26def6', '#1ac13e'],
grid: {
containLabel: true,
top: '20%',
left: 20,
right: 20,
bottom: 20
},
xAxis: {
type: 'category',
data: xAxisData,
axisLabel: {
interval: 0,
color: '#1D2129',
formatter: function (value, index) {
var type = data[index].type;
console.log(`{${type}|${value}}`);
return `{${type}|${value}}`
},
rich: typeColors
}
},
yAxis: {
type: 'value',
},
series: [
{
name: '工作日',
data: seriesData,
type: 'bar'
},
{
name: '节假日',
data: seriesData2,
type: 'bar'
},
]
};
myChart.setOption(option);
</script>
</body>