场景:做某基金中的股票收益分析的时候,要把收益前五和亏损前5的股票给列出来;实现如效果图:
要求
- 显示股票收益前五和亏损前五
- 通过Echarts实现要求左绿右红
效果图
代码实现,重要步骤已经进行注释
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>股票盈亏前5正负交错轴显示</title>
<!-- 引入 echarts.js -->
<script src="https://cdn.bootcss.com/echarts/4.2.1/echarts.min.js"></script>
</head>
<body>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
// 设置标签名的显示位置
var labelLeft = {
normal: {
position: 'left'
}
};
var labelRight = {
normal: {
position: 'right'
}
};
option = {
title: {
text: '股票盈亏TOP5',
subtext: '明显是模拟的数据~',
x: 'center'
},
tooltip: {
trigger: 'axis',
axisPointer: { // 坐标轴指示器,坐标轴触发有效
type: 'shadow' // 默认为直线,可选为:'line' | 'shadow'
}
},
grid: {
top: 80,
bottom: 30
},
xAxis: {
type: 'value',
position: 'bottom',
splitLine: {lineStyle: {type: 'dashed'}},
},
yAxis: {
type: 'category',
axisLine: {show: false},
axisLabel: {show: false},
axisTick: {show: false},
splitLine: {show: false},
// 股票名称。要与series数据顺序匹配正确
data: ['股票1', '股票2', '股票3', '股票4', '股票5',
'股票6', '股票7', '股票8', '股票9', '股票10',
]
},
series: [
{
name: '盈亏(亿元)',
type: 'bar',
stack: '总量',
label: {
normal: {
show: true,
formatter: '{b}'
}
},
// 表中从下到上,从最大亏损到最大盈利
data: [
{value: -1.07, label: labelLeft},
{value: -0.89, label: labelLeft},
{value: -0.33, label: labelLeft},
{value: -0.23, label: labelLeft},
{value: -0.03, label: labelLeft},
{value: 0.36, label: labelRight},
{value: 0.89, label: labelRight},
{value: 1.08, label: labelRight},
{value: 1.68, label: labelRight},
{value: 2.24, label: labelRight},
],
// 添加颜色显示规则
// 大于等于0红色; 小于0为绿色
itemStyle: {
normal: {
color: function (params) {
return params.value >= 0 ? "red" : "green";
}
}
}
}
]
};
myChart.setOption(option);
</script>
</body>
</html>