echarts实现折线图根据数值进行分层
这里为了方便展示我把x轴和y轴都进行了隐藏,展示出来的效果就是如图所示。
接下来我们开始完成图标的形成:
我们需要准备一组数据,并且提前获取我们的标准值,比如图上的20
根据标准值/最大值
,我们可以计算出标准值应该存在图表的位置
var warnLine = 20; // 标准值
var maxVal = Math.max.apply(
null,
[20, 26, 22, 30, 25, 28, 14, 24, 16, 28, 18]
); // 最大值
var warnProp = warnLine / maxVal; //标准值对应的位置百分比
先完成正常的折线图绘制代码,然后我们需要在series上加上markLine的配置,这个配置就是标准线的配置
markLine: {
silent: true,
symbol: "none",
label: {
position: "end",
formatter: "20%", //这里的数值可以写成动态的
color: "#EA2626",
},
data: [
{
silent: false,
lineStyle: {
type: "dashed",
color: "#EA2626",
},
yAxis: warnLine, //警戒线在y轴上的坐标
},
],
},
然后我们就可以进行分区了,重点是使用了areaStyle的配置,根据我们上面计算的数值进行颜色的配置达成分区的效果
areaStyle: {
normal: {
color: {
type: "linear",
x: 0,
y: 1,
x2: 0,
y2: 0,
colorStops: [
{
offset: 0,
color: "rgba(52, 121, 236, 0)",
},
{
offset: warnProp / 3,
color: "rgba(52, 121, 236, 0.2)",
},
{
offset: warnProp,
color: "rgba(52, 121, 236, 0.8)",
},
{
offset: warnProp,
color: "rgba(255, 92, 92, 0.6)",
},
{
offset: warnProp + (1 - warnProp) / 3,
color: "rgba(255, 92, 92, 0.9)",
},
{
offset: 1,
color: "rgba(255, 92, 92, 1)",
},
],
global: false,
},
},
},
上面对应的offset也可以根据自己的需要进行修改,最终达成自己想要的效果。
原理就是以上这样,话不多说,源码奉上:
humidityEcharts() {
var warnLine = 20;
var maxVal = Math.max.apply(
null,
[20, 26, 22, 30, 25, 28, 14, 24, 16, 28, 18]
);
var warnProp = warnLine / maxVal;
this.rightCnetrEcharts = echarts.init(
document.getElementById("right_center_echarts")
);
document
.getElementById("right_center_echarts")
.removeAttribute("_echarts_instance_");
let option = {
legend: {
show: false,
},
tooltip: {
show: false,
trigger: "axis",
},
grid: {
left: 0,
right: "10%",
bottom: 0,
top: 0,
},
xAxis: {
type: "category",
axisLine: {
show: false,
},
boundaryGap: false,
axisTick: {
show: false,
},
axisLabel: {
show: false,
},
data: [1, 2, 3, 4, 5, 6, 8, 9, 10, 11],
},
yAxis: [
{
type: "value",
axisTick: {
show: false,
},
axisLabel: {
show: false,
},
axisLine: {
show: false,
},
splitLine: {
show: false,
},
},
],
series: [
{
data: [20, 26, 22, 30, 25, 28, 14, 24, 16, 28, 18],
type: "line",
markLine: {
silent: true,
symbol: "none",
label: {
position: "end",
formatter: "20%",
color: "#EA2626",
},
data: [
{
silent: false,
lineStyle: {
type: "dashed",
color: "#EA2626",
},
yAxis: warnLine, //警戒线在y轴上的坐标
},
],
},
symbolSize: false,
smooth: true,
lineStyle: {
color: "transparent",
width: 1,
},
itemStyle: {
color: "#EA2626",
borderColor: "#fff",
borderWidth: 0,
},
connectNulls: true,
symbol: "circle",
yAxisIndex: 0,
areaStyle: {
normal: {
color: {
type: "linear",
x: 0,
y: 1,
x2: 0,
y2: 0,
colorStops: [
{
offset: 0,
color: "rgba(52, 121, 236, 0)",
},
{
offset: warnProp / 3,
color: "rgba(52, 121, 236, 0.2)",
},
{
offset: warnProp,
color: "rgba(52, 121, 236, 0.8)",
},
{
offset: warnProp,
color: "rgba(255, 92, 92, 0.6)",
},
{
offset: warnProp + (1 - warnProp) / 3,
color: "rgba(255, 92, 92, 0.9)",
},
{
offset: 1,
color: "rgba(255, 92, 92, 1)",
},
],
global: false,
},
},
},
},
],
};
option && this.rightCnetrEcharts.setOption(option, true);
},