echarts实现控制图(设置阈值上下限超出变色)

文章介绍了如何使用ECharts库创建一个控制图,其中数据超出预设的最小值和最大值范围时会变色,并显示平均值、最大值和最小值标记。开发者分享了详细的代码实例和配置选项。
该文章已生成可运行项目,

echarts实现控制图组件,拓展超出阈值变色显示,图中标记平均值及最大值和最小值

代码如下:

<template>
    <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
    import echarts from 'echarts'
    require('echarts/theme/macarons') // echarts theme

    export default {
        props: {
            className: {
                type: String,
                default: 'chart'
            },
            width: {
                type: String,
                default: '100%'
            },
            height: {
                type: String,
                default: '400px'
            },
            dataList: {
                type: Array,
                default: []
            }
        },
        data() {
            return {
                chart: null,
                xData: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"],
                serieData: [10, 30, 20, 30, 60, 20, 10, 30, 30, 20, 30],
                minMarks: 19,
                maxMarks: 50,
            }
        },
        mounted() {
            this.$nextTick(() => {
                this.initChart()
            })
        },
        beforeDestroy() {
            if (!this.chart) {
                return
            }
            this.chart.dispose()
            this.chart = null
        },
        watch: {
            dataList(val, oldVal) {//普通的watch监听
                this.initChart()
            }
        },
        methods: {
            initChart() {
                this.chart = echarts.init(this.$el, 'macarons')
                this.chart.setOption({
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {},
                    grid: {
                        top: "15%",
                        left: '3%',
                        right: '8%',
                        bottom: '3%',
                        containLabel: true
                    },
                    xAxis: [
                        {
                            name: "日期",
                            type: 'category',
                            data: this.xData,
                            axisTick: {
                                show: false,
                                alignWithLabel: true
                            },
                            axisLabel: {
                                show: true,
                            },
                            axisLine: {
                                show: true,
                                lineStyle: {
                                    color: '#456980 ',
                                }
                            },

                        }
                    ],
                    yAxis: {
                        name: "阅读量",
                        type: 'value',
                        axisTick: {
                            alignWithLabel: true,
                        },
                        axisLine: {
                            show: true,
                            lineStyle: {
                                color: '#456980',
                            }
                        },
                        splitLine: {
                            show: true,
                            lineStyle: {
                                color: '#456980',
                            }
                        },
                        axisLabel: {
                            show: true,
                        }
                    },
                    series: [
                        {
                            name: '',
                            type: 'line',
                            data: this.serieData,
                            label: {
                                normal: {
                                    show: true,
                                    position: 'top',
                                    formatter: '{c}',
                                    textStyle: {
                                        color: '#fff',
                                        fontWeight: 'normal',
                                        fontSize: '12',
                                    },
                                }
                            },
                            // smooth: false,
                            // symbol: 'none',//设置线型
                            lineStyle: {
                                // 这里不能设置颜色,不然会以这个为准,设置的范围变色将不起作用
                                width: 2
                            },
                            itemStyle: {
                                normal: {
                                    show: true,
                                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                        offset: 0,
                                        color: 'rgba(49, 200,190, 0.8)'
                                    }, {
                                        offset: 1,
                                        color: 'rgba(16, 127,159, 0.8)'
                                    }]),
                                    shadowColor: 'rgba(0, 0, 0, 0.1)',
                                    shadowBlur: 10
                                }
                            },
                            markPoint: {
                                data: [
                                    { 
                                        type: 'max',
                                        name: 'Max',
                                        itemStyle: { color: '#F2761D' }
                                    },{ 
                                        type: 'min', 
                                        name: 'Min',
                                        itemStyle: { color: '#605D5A' }
                                    }
                                ]
                            },
                            //标记的线1
                            markLine: {
                                symbol: ['circle', 'arrow'], //箭头
                                silent: true,
                                lineStyle: {
                                    // type: 'dashed'//虚线
                                    type: 'solid'//实线
                                },
                                data: [
                                    { 
                                        type: 'average', 
                                        name: 'Avg',
                                        label: {
                                            formatter: "平均值:{c}",
                                        } 
                                    },
                                    {
                                        yAxis: this.minMarks,
                                        lineStyle: {
                                            width: 3,
                                            color: '#00ff00'
                                        },
                                        label: {
                                            show: true,
                                            color: '#00ff00',
                                            fontSize: '14',
                                            position: "end", //将警示值放在哪个位置,三个值“start”,"middle","end"  开始  中点 结束
                                            formatter: "预警下线:{c}",
                                        }
                                    }, {
                                        yAxis: this.maxMarks,
                                        lineStyle: {
                                            width: 3,
                                            color: '#ff0000'
                                        },
                                        label: {
                                            show: true,
                                            color: '#ff0000',
                                            fontSize: '14',
                                            position: "end", //将警示值放在哪个位置,三个值“start”,"middle","end"  开始  中点 结束
                                            formatter: "预警上线:{c}",
                                        }
                                    }

                                ]
                            },
                        },

                    ],
                    visualMap: {
                        show: false,
                        // seriesIndex: [0, 1], // 虽然可以指定多个series,但是线的颜色只能设置一条
                        seriesIndex: 0,
                        pieces: [{
                            gt: this.maxMarks,
                            color: '#F2761D'
                        }, {
                            lt: this.minMarks,
                            color: '#605D5A'
                        }],
                        outOfRange: { // 在选中范围外 的视觉元素,这里设置在正常范围内的图形颜色
                            color: '#1890FF',
                        },
                    },
                })
            }
        }
    }
</script>

效果图:

本文章已经生成可运行项目
<think>好的,我现在需要帮助用户解决在recharts实现折线图根据阈值下限变色的需求,并且用户希望使用TypeScript(tsx)。首先,我得回忆一下recharts库的相关组件和功能,特别是如何自定义折线图的颜色。 用户的问题是关于设置阈值超出部分变色,这可能涉及到如何根据数据点的值动态改变线段或点的颜色。根据之前的对话历史,用户之前遇到过类型不匹配的问题,所以这次可能需要特别注意TypeScript的类型定义。 首先,我应该考虑recharts的Line组件有哪些属性可以自定义颜色。可能用到的是stroke属性,但默认情况下stroke是单一颜色。要实现根据阈值变色,可能需要将折线分段,不同颜色段使用不同的stroke。或者,使用一个函数来动态返回颜色值。 查阅recharts文档,发现Line组件的stroke属性可以接受一个函数,该函数返回颜色字符串。但是可能仅适用于每个数据点的点颜色,而不是线段颜色。线段本身的颜色可能需要更复杂的处理,比如使用多个Line组件来绘制不同颜色的线段,或者使用自定义的线段组件。 另外,用户可能需要将超出阈值的数据点用不同颜色显示。这可以通过设置dot属性,根据数据点的值返回不同的颜色或样式。同时,可能需要参考之前的解决方案,确保返回的是ReactElement而不是null,避免类型错误。 接下来,需要思考如何将数据分段。例如,当数据点的y值超过上限或低于下限时,该线段段的颜色需要改变。这可能需要将原始数据分割成多个段,每个段应用不同的颜色。例如,遍历数据数组,找到超过阈值的点,然后分割成多个线段,每个线段使用对应的颜色。 或者,使用自定义的线段组件,例如在Line组件中使用自定义的stroke函数,根据当前数据点的值和下一个点的值来判断是否需要改变颜色。但这可能需要访问前后数据点的值,可能比较复杂。 另一个可能的方案是使用Area组件结合渐变,但用户明确提到的是折线图,所以可能更倾向于使用Line组件。 还需要考虑TypeScript的类型定义,确保自定义的函数和组件符合recharts预期的类型,避免出现之前的类型不匹配错误。例如,stroke属性的函数参数类型是否正确,返回的颜色是否是字符串类型,或者是否允许undefined等。 可能的步骤包括: 1. 准备示例数据,包含x和y值。 2. 定义阈值上限和下限,比如upperThreshold和lowerThreshold。 3. 创建一个自定义的stroke函数,根据数据点的y值返回对应的颜色。 4. 使用Line组件的stroke属性和dot属性来应用动态颜色。 5. 处理线段颜色分段的问题,可能需要将数据分割成多个部分,每个部分使用不同的Line组件绘制。 但是,线段颜色分段可能比较复杂,因为折线图的线段是连接两个数据点的,所以需要判断两个点之间的线段是否跨越了阈值,从而决定颜色。这可能需要遍历数据点,生成多个线段段,并为每个段创建对应的Line组件。 例如,遍历数据数组,对每两个相邻的点进行检查,如果其中一个点超过阈值,则分割线段,并设置对应的颜色。这种方法需要生成多个Line组件,每个组件绘制不同颜色的线段段。 或者,使用一个自定义的线段渲染器,动态计算每个线段的颜色。这可能需要使用recharts的自定义组件功能,比如提供自定义的stroke属性函数,或者使用自定义的shape组件来绘制线段。 此外,还需要处理数据点的样式,比如超出阈值的点用红色显示,正常点用绿色。这可以通过dot属性实现,返回一个自定义的圆点组件,根据数据点的值选择颜色。 在TypeScript方面,需要注意函数参数的类型,例如dot属性接受的函数类型,stroke属性的函数类型是否正确,确保不会出现类型错误。例如,dot属性的函数需要返回ReactElement或者null,但根据之前的错误,可能需要确保不返回null,而是返回空元素如<></>。 总结可能的实现方案: 1. 使用多个Line组件,每个对应不同颜色段,通过处理数据分割实现。 2. 使用自定义的shape属性,动态绘制不同颜色的线段。 3. 结合stroke和dot属性,根据每个数据点的值动态设置颜色,但可能只能改变点和线段的整体颜色,无法分段。 考虑到实现复杂度,可能第二种方法更可行,但需要更深入的recharts知识。或者,如果用户只需要根据单个数据点的值改变线段颜色,而不是线段段,那么可以简单使用stroke属性的函数。 例如,stroke属性可以是一个函数,根据当前数据点的值返回颜色,但这样可能每个线段段的颜色由起点决定,而不是整段。这可能不符合用户需求,因为线段连接两个点,如果其中一点超出阈值,可能需要整个线段变色。 因此,可能需要更复杂的数据处理,生成多个线段段,每个段颜色由两个端点决定。例如,如果两个点都在阈值内,线段颜色为绿色;如果至少有一个点超出,则颜色为红色。 这种情况下,需要将原始数据分割成多个段,每个段的两个端点都在同一颜色区域,然后为每个段创建一个Line组件,设置对应的颜色。 具体实现步骤可能如下: 1. 遍历数据数组,生成多个线段段。 2. 对每个段判断颜色:如果段中任意点超出阈值,颜色为红色,否则绿色。 3. 为每个段生成对应的Line组件,使用该颜色。 这可能需要编写一个函数来处理数据的分割,并生成多个Line组件。 另外,可能还需要处理数据点之间的插值,例如使用type="linear"或其他插值类型,确保线段正确连接。 在TypeScript中,需要确保生成的数据段符合Line组件需要的类型,例如dataKey正确,数据格式正确。 此外,可能还需要添加图例、提示工具等其他元素,但用户主要关注的是变色功能,所以这部分可能不需要详细说明。 最后,给出一个示例代码,展示如何实现分段变色,并确保TypeScript类型正确,避免之前的类型错误。</think>以下是使用Recharts实现折线图阈值变色功能的完整TypeScript解决方案,通过分步说明和代码注释帮助您理解实现原理: --- ### 一、核心思路 1. **数据分段处理**:将原始数据切割为多个连续区间,根据相邻数据点与阈值的关系确定线段颜色 2. **动态渲染策略**: - **线段颜色**:使用多个`<Line>`组件分别渲染不同颜色的线段 - **数据点颜色**:通过`dot`属性动态控制点的颜色 3. **阈值可视化**:添加参考线标记阈值边界 --- ### 二、完整实现代码 (TSX) ```tsx import React from 'react'; import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ReferenceLine } from 'recharts'; // 阈值配置类型 interface ThresholdConfig { upper: number; // 上限 lower: number; // 下限 normalColor: string; // 正常颜色 abnormalColor: string; // 异常颜色 } // 分段数据类型 interface DataSegment { data: Array<{ x: number | string; y: number }>; color: string; } // 生成分段数据的函数 const createSegments = ( data: Array<{ x: number | string; y: number }>, threshold: ThresholdConfig ): DataSegment[] => { const segments: DataSegment[] = []; let currentSegment: DataSegment = { data: [], color: threshold.normalColor }; data.forEach((point, index) => { const isAbnormal = point.y > threshold.upper || point.y < threshold.lower; const nextPoint = data[index + 1]; // 当前点颜色判断 const currentColor = isAbnormal ? threshold.abnormalColor : threshold.normalColor; // 新建分段的情况: // 1. 当前段为空 // 2. 颜色发生变化 if (currentSegment.data.length === 0 || currentSegment.color !== currentColor) { if (currentSegment.data.length > 0) { segments.push(currentSegment); } currentSegment = { data: [point], color: currentColor }; } else { currentSegment.data.push(point); } // 处理跨阈值的线段 if (nextPoint) { const nextIsAbnormal = nextPoint.y > threshold.upper || nextPoint.y < threshold.lower; if (isAbnormal !== nextIsAbnormal) { segments.push(currentSegment); currentSegment = { data: [point], color: nextIsAbnormal ? threshold.abnormalColor : threshold.normalColor }; } } }); if (currentSegment.data.length > 0) { segments.push(currentSegment); } return segments; }; // 主组件 const ThresholdLineChart: React.FC<{ data: Array<{ x: number | string; y: number }>; threshold: ThresholdConfig; }> = ({ data, threshold }) => { const segments = createSegments(data, threshold); return ( <LineChart width={600} height={400} margin={{ top: 20, right: 30, left: 20, bottom: 20 }} > <CartesianGrid strokeDasharray="3 3" /> <XAxis dataKey="x" /> <YAxis /> <Tooltip /> {/* 绘制阈值参考线 */} <ReferenceLine y={threshold.upper} stroke="red" strokeDasharray="5 5" /> <ReferenceLine y={threshold.lower} stroke="red" strokeDasharray="5 5" /> {/* 动态渲染分段线段 */} {segments.map((segment, index) => ( <Line key={`line-${index}`} type="linear" dataKey="y" data={segment.data} stroke={segment.color} strokeWidth={2} dot={({ cy, payload }) => ( <circle cx={payload.x} cy={cy} r={4} fill={payload.y > threshold.upper || payload.y < threshold.lower ? threshold.abnormalColor : threshold.normalColor } /> )} /> ))} </LineChart> ); }; // 使用示例 const App: React.FC = () => { const demoData = [ { x: '00:00', y: 25 }, { x: '01:00', y: 40 }, { x: '02:00', y: 15 }, { x: '03:00', y: 32 }, { x: '04:00', y: 28 }, { x: '05:00', y: 50 } ]; const thresholdConfig = { upper: 35, lower: 20, normalColor: '#82ca9d', abnormalColor: '#ff4040' }; return ( <ThresholdLineChart data={demoData} threshold={thresholdConfig} /> ); }; export default App; ``` --- ### 三、关键实现解析 #### 1. 数据分段算法 (`createSegments`) - **遍历策略**:逐个检查数据点及其后续点 - **颜色判断逻辑**: ```typescript const isAbnormal = point.y > upper || point.y < lower ``` - **分段规则**: - 当前点颜色变化时创建新分段 - 相邻点颜色不同时强制分割线段 #### 2. 动态点渲染 (`dot`属性) ```tsx dot={({ cy, payload }) => ( <circle fill={payload.y超出阈值 ? 异常色 : 正常色} /> )} ``` #### 3. 阈值参考线 ```tsx <ReferenceLine y={threshold.upper} stroke="red" strokeDasharray="5 5" /> ``` --- ### 四、效果优化建议 1. **颜色过渡**:使用线性渐变实现平滑颜色过渡 ```tsx <defs> <linearGradient id="gradient" x1="0" y1="0" x2="1" y2="0"> <stop offset="50%" stopColor="green" /> <stop offset="50%" stopColor="red" /> </linearGradient> </defs> ``` 2. **动画效果**:添加`animationDuration`提升视觉体验 ```tsx <Line animationDuration={500} /> ``` 3. **阈值区间标记**:使用`<ReferenceArea>`突出显示安全区域 ```tsx <ReferenceArea y1={lower} y2={upper} fill="rgba(130, 202, 157, 0.2)" /> ``` --- ### 五、典型应用场景 1. 工业监控(温度/压力超限报警) 2. 医疗监护(生命体征异常监测) 3. 金融风控(指标阈值预警) 4. 环境监测(污染指数超标提醒) --- 通过这种实现方式,您可以获得: - 精确的线段颜色分段控制 - 动态交互式数据点 - 清晰的阈值可视化标识 - 完全类型安全的TypeScript实现
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值