记录一下开发中Echarts的应用

1,474 阅读4分钟

1、对这个趋势图进行总结

image.png

(1)图例组件legend

legend: {
    selectedMode: false, // 取消图例上的点击事件
    orient: 'horizontal', // 横着展示
    top: 0,
    left: 15,
    padding: [1, 0],
    data: legentData, // legentData
    textStyle: { // 字体样式变化
        fontSize: '11px',
        color: '#999999',
        lineHeight: 15,
    },
    icon: 'circle',
    itemGap: 8, // 图例每项之间的间隔
    itemHeight: 8, // 改变圆圈大小
    itemWidth: 8, // 改变圆圈的宽度
},
  • legend. type

图例的类型。可选值:'plain'普通图例。缺省就是普通图例。'scroll'可滚动翻页的图例。当图例数量较多时可以使用。

  • legend. icon

图例项的 icon:'circle'(圆形)、'rect'(矩形)、'roundRect'(圆矩形)、'triangle'(三角形)、'diamond'(菱形)、'pin'(倒水滴)、'arrow'(箭头)、'none'(无)

  • legend. data

图例的数据数组

  • legend. orient

图例列表的布局朝向。'horizontal'(水平)、'vertical'(垂直)

  • legend. padding

图例内边距,单位px,默认各方向内边距为5,接受数组分别设定上右下左边距。

  • legend. itemGap

图例每项之间的间隔。横向布局时为水平间隔,纵向布局时为纵向间隔。

  • legend. itemWidth

图例标记的图形宽度。(icon的宽度)

  • legend. itemHeight

图例标记的图形高度。(icon的高度)

  • legend. selectedMode 

图例选择的模式,控制是否可以通过点击图例改变系列的显示状态。默认开启图例选择,可以设成 false 关闭。true的时候点击图例的某一项消失

(2)tooltip提示框组件

tooltip: {
    trigger: 'axis',
    axisPointer: { // 坐标轴指示器,坐标轴触发有效
        type: 'line', // 默认为直线,可选为:'line' | 'shadow'
        lineStyle: { // 指示线的样式设置
            color: 'rgba(0,0,0,0.1)'
        }
    },
    textStyle: {
        color: '#999999',
        fontSize: 10,
        lineHeight: 20,
    },
    backgroundColor: ' #FFFFFF',
    extraCssText: 'z-index:0;box-shadow: 0 0 3px rgba(0, 0, 0, 0.3); padding: 5px 10px;', // 额外附加到浮层的 css 样式
    formatter: function(params) {// 提示框浮层内容格式器
        let domStr = '';
        let time = params[0].name;

        domStr += '<div>' +
        '<p style="line-height: 20px;">' + time + '</p>';
        for(let i = 0; i < params.length; i++) {
            let param = params[i];
            let seriesName = param.seriesName;// 图例名称
            let value = param.value;// y轴值
            if(!value) {
                return;
            }
            let mark = _this.handleTip(seriesName, Number(value));
            domStr +=
            '<div style="display: flex; align-items: center;  justify-content: space-between;font-size: 12px;line-height: 20px;">'
                + '<p>'
                    + '<span style="margin-right: 5px;width:24px;display: inline-block;font-weight: 700;'
                        + `${mark === '偏高' ? 'color:#FA6400' : mark === '偏低' ? 'color: #29CCB1' : 'color: #333333'}`
                        + '">'
                        + value
                    + '</span>'
                    + '<span style="font-size: 10px; padding: 1px 2px;margin-right: 10px;border-radius: 2px;'
                        + `${mark === '偏高' ? 'background: #FFF3EB;color:#FA6400' : mark === '偏低' ? 'background: #E6FAF7;color: #29CCB1' : ''}`
                        + '">'
                        + `${mark ? mark : ''}`
                    + '</span>'
                + '</p>'
                + '<p>' + seriesName + '</p>'
            + '</div>';
        }
        domStr += '</div>';
        return domStr;
    }
},

(3)y轴

yAxis: {
    name: unitLabel[healthRecordType], // 设置y轴名称
    nameGap: 20, // 坐标轴名称与轴线之间的距离。
    nameTextStyle: {
        padding: [0, 0, 0, -20] // 四个数字分别为上右下左与原位置距离
    },
    min: 0,
    max: vMax,
    // max: Math.ceil(verticalMax * (1 + 0.2)),
    // splitNumber: 5, // y轴分割线的个数
    interval: vMax / 5,
    type: 'value',
    axisTick: {// 在坐标轴上保证刻度线和标签对其
        show: false, // 去掉刻度线
        alignWithLabel: true
    },
    axisLine: {// 去掉y轴
        show: false,
        lineStyle: {
            color: '#999'
        },
        textStyle: {
            color: '#999',
            fontSize: '12',
            align: 'right'
        }
    }
},

(4)x轴

对时间的处理

 // 获取当前时间的前三十天 方法
handleDate = () => {
    let date = [];
    let oneDay = 24 * 3600 * 1000;
    let base = new Date();
    for (var i = 0; i < 30; i++) {
        let model = base - oneDay * i;
        var now = new Date(model);
        let dateStr = moment(now).format('YYYY-MM-DD');
        date.push(dateStr);
    }
    return date.reverse();
}

echarts 的x轴

xAxis: {
    type: 'category',
    boundaryGap: true, // 坐标轴两边留白策略
    interval: 'auto',
    data: dateList,
    show: true,
    axisTick: {// 在坐标轴上保证刻度线和标签对其
        show: false, // 去掉刻度线
        alignWithLabel: true
    },
    axisLine: {// 去掉x轴
        show: false,
        lineStyle: {
            color: '#999'
        },
        textStyle: {
            color: '#999',
            fontSize: '12',
        }
    },
    axisLabel: {// 对x轴的刻度线的字体进行处理
        formatter: function (value) {
            let dateStr = moment(value).format('MMDD');
            return dateStr;
        }
    }
},

(5)grid

折线图的位置

grid: { 
    top: '20%', 
    left: '16px', 
    right: '16px', 
    bottom: '5%', 
    containLabel: true 
},

2、折线图(轮动 + 自适应宽度)

根据代码注释查找自己想要的吧

截屏2022-11-04 14.58.48.png

截屏2022-11-04 14.58.59.png


constructor(props) {
        super(props);
        this.myChart = null;
    }
    componentDidMount() {
        let { id, chartTitle, extraChartTitle, smooth } = this.props;
        let chartDom = document.getElementById(id);
        this.myChart = echarts.init(chartDom);
        let option = {
            showSymbol: true,// 高亮时,也就是鼠标划上去有圆点
            symbol: 'emptyCircle',
            title: {
                text: extraChartTitle ? chartTitle + '(' + extraChartTitle + ')' : chartTitle,
                textStyle: {
                    color: 'rgba(0, 0, 0, 0.85)',
                    fontSize: 16,
                    fontWeight: 400,
                    lineHeight: 16
                },
                // padding: [0, 7, 0, 0]
            },
            grid: {// 设置曲线图的位置
                left: '60',
                top: '-1%',
                right: '1%',
                bottom: '5%',
                containLable: true,
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,// 坐标轴两边留白策略,false没有留白,可以使x轴的第一个点和y轴的第一个点重
                axisTick: {
                    // 在坐标轴上保证刻度线和标签对其
                    show: true, // 去掉刻度线
                    alignWithLabel: true
                },
                axisLine: {
                    lineStyle: {
                        color: 'rgba(0, 0, 0, 0.25)'
                    },
                },
                data: [
                    '2022/05/29',
                    '2022/05/30',
                    '2022/06/01',
                    '2022/06/02',
                    '2022/06/03',
                    '2022/06/04',
                    '2022/06/05',
                    '2022/06/06',
                    '2022/06/07',
                    '2022/06/08',
                ]
            },
            yAxis: {
                type: 'value',
                axisTick: {
                    // 在坐标轴上保证刻度线和标签对其
                    show: false, // 去掉刻度线
                    alignWithLabel: true
                },
                splitLine: {// y轴上的分割线的样式
                    show: true,
                    lineStyle: {
                        color: 'rgba(0, 0, 0, 0.05)'
                    },
                },
                axisLine: {// 去掉Y轴
                    show: false,
                    lineStyle: {
                        color: 'rgba(0, 0, 0, 0.45)',
                        fontSize: '13',
                    },
                },
            },
            series: [
                {
                    data: [820, 9032, 10001, 3501, 7501, 7701, 9934, 10290, 13330, 123320],
                    type: 'line',
                    smooth: smooth || false,// true的时候为曲线,false的时候是折线
                    showSymbol: false,// 设置曲线上默认没有圆点,当鼠标移到曲线上并展示tooltip时展示圆点
                    areaStyle: {// 设置阴影面积
                        normal: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [// 设置渐变颜色
                                {
                                    offset: 0,
                                    color: 'rgba(22, 128, 242, 0.22)' // 0% 处的颜色
                                },
                                {
                                    offset: 1,
                                    color: 'rgba(22, 128, 242, 0.03)' // 100% 处的颜色
                                }
                            ]) //背景渐变色
                        }
                    },
                    lineStyle: { // 设置线条的style等
                        normal: {
                            color: 'rgba(22, 128, 242, 1)',
                        },
                    },
                    itemStyle: {// 线条上的点
                        normal: {
                            symbol: 'none',
                            color: 'rgba(22, 128, 242, 1)',//外框颜色
                        },
                        emphasis: {
                            symbol: 'emptyCircle',
                            color: "rgba(22, 128, 242, 1)",//移入后的颜色
                        }
                    },

                }
            ],
            tooltip: {
                show: true,
                trigger: 'axis',
                axisPointer: {
                    // 坐标轴指示器,坐标轴触发有效,cross横纵坐标都有指示线,就像上图展示的那样,line就是只有横坐标上有指示线
                    type: 'cross',
                    lineStyle: {
                        // 指示线的样式设置
                        color: 'rgba(0,0,0,0.1)'
                    }
                },
                extraCssText:
                    'background: #FFFFFF;box-shadow: 0px 9px 28px 8px rgba(0,0,0,0.05), 0px 6px 16px 0px rgba(0,0,0,0.08), 0px 3px 6px -4px rgba(0,0,0,0.12);border-radius: 8px;opacity: 0.95; padding: 15px 14px; 14px', // 额外附加到浮层的 css 样式
                formatter: function (params) {
                    return (
                        '<div>'
                        + '<p style="font-size: 12px;font-weight: 400;color: rgba(0, 0, 0, 0.45);line-height: 12px;margin-bottom:7px">'
                        + params[0].axisValue
                        + '</p>'
                        + '<p style="font-size: 13px;font-weight: 400;line-height: 18px;margin-bottom:0px">'
                        + '<span style="color: rgba(0, 0, 0, 0.65);display:inline-block;margin-right:4px">'
                        + chartTitle
                        + '</span>'
                        + '<span style="color: #8C8C8C;">'
                        + params[0].data + '</span>'
                        + '</p>'
                        + '</div>'
                    )
                }
            },
            // ---------------------图表可滑动-----------------------
            dataZoom: [// 10条数据,图表上只展示5个刻度线,图表可滑动
                {
                    type: 'inside',
                    zoomLock: true,
                    startValue: 0,
                    endValue: 5
                }
            ]
        };

        option && this.myChart.setOption(option);
        
        // ---------------------自适应宽度---------------------------
        // 这里监听图表的父级的宽度做到自适应宽度
        window.addEventListener("resize", () => {
            this.myChart.resize();
        });
    }
    componentWillUnmount() {
        // ------------------自适应宽度 监听记得销毁-------------------
        window.removeEventListener("resize", () => {
            this.myChart.resize();
        });
    }

3、对饼状图的记录1

(1)设置两列legend

截屏2022-04-24 下午4.33.10.png

option的设置
 const option = {
      // 饼状图每项的颜色设置
      color: ['#C80000 ', '#F96432', '#FA8C16', '#FADB14 ', '#41B3E8', '#025EA5'],
      tooltip: {
        trigger: 'item',
      },
      legend: {
        bottom: '10%', // 设置legend于底部的距离
        left: 'center', // 设置legend于居中
        itemWidth: 4, // 设置每一个legend前面的图标的宽度
        itemHeight: 9, // 设置每一个legend前面的图标的高度
        // 往下是设置 legend 可以展示几列的
        width: 360, // 设置legend区域整体的宽度
        formatter: function (name) {
          return '{a|' + name + '}';
        },
        textStyle: {
          backgroundColor: 'transparent', // 文字块背景色,一定要加上,否则对齐不会生效
          rich: {
            a: {
              width: 120, // 每一项的宽度
            },
          },
        },
      },
      series: [
        {
          type: 'pie',
          bottom: '20%',
          radius: ['40%', '60%'],
          avoidLabelOverlap: false,
          label: {
            show: false, // 正常情况下,饼图的每一项的label在饼图上不展示
          },
          emphasis: {
            label: {
              // 鼠标移动到饼图上,label的变化
              show: true,
              fontSize: '14',
              fontWeight: 'bold',
            },
            labelLine: {
              // 鼠标移动到饼图上,label是否加线
              show: true,
            },
          },
          data: data,
        },
      ],
    };

(2)自定义legend: 给每一个legend添加百分比数据

截屏2022-04-25 上午11.07.12.png

legend的设置
legend: {
    bottom: '10%', // 设置legend于底部的距离
    left: 'center', // 设置legend于居中
    itemWidth: 4, // 设置每一个legend前面的图标的宽度
    itemHeight: 9, // 设置每一个legend前面的图标的高度
    // 往下是设置 legend 可以展示几列的
    width: 360, // 设置legend区域整体的宽度
    formatter: function (name) {
      // 自定义legend : 给 每一个 legend 添加 百分比的数据
      let than = option.series[0].data; //获取series中的data
      let total = 0;
      let tarValue;
      for (let i = 0, l = than.length; i < l; i++) {
        total += than[i].value;
        if (than[i].name == name) {
          tarValue = than[i].value;
        }
      }
      let p = (tarValue / total) * 100;
      return '{a|' + name + ' ' + ' ' + p.toFixed(2) + '%' + '}';
    },
    textStyle: {
      backgroundColor: 'transparent', // 文字块背景色,一定要加上,否则对齐不会生效
      rich: {
        a: {
          width: 140, // 每一项的宽度
        },
      },
    },
},

(3)自定义label: 给label加上数据

截屏2022-04-25 上午11.07.12.png

label的设置
 series: [
    {
      type: 'pie',
      bottom: '20%',
      radius: ['40%', '60%'],
      avoidLabelOverlap: false,
      label: {
        show: false, // 正常情况下,饼图的每一项的label在饼图上不展示
        // 自定义label: 展示名称和数据
        formatter: function (d) {
          return d.name + ' ' + d.value;
        },
      },
      emphasis: {
        label: {
          // 鼠标移动到饼图上,label的变化
          show: true,
          fontSize: '13',
          fontWeight: 'bold',
        },
        labelLine: {
          // 鼠标移动到饼图上,label是否加线
          show: true,
        },
      },
      data: data,
    },
  ],

(4)给饼图加白色背景和阴影

截屏2022-12-07 15.14.13.png

方式一: 采用叠加思想,在饼图下面加一个空白的饼图

 series: [
 {
     你自己想要的饼图
 },{
     // 叠加的底饼图
      {
        type: 'pie',
        radius: ['33.5%', '46.5%'],
        top: -120,
        showEmptyCircle: true,
        emptyCircleStyle: {
          color: "#fff",// 底饼图的背景颜色
          // 设置阴影
          shadowColor: 'rgba(91, 140, 255, 0.11)',
          shadowBlur: 22,
          shadowOffsetX: 0,
          shadowOffsetY: 6,
        },
      }
 }
 ]

方式二:给每一个itemStyle添加边框和阴影

 series: [
 {
      type: 'pie',
      radius: ['35%', '45%'],
      top: -120,
      itemStyle: {
          borderColor: '#fff',
          borderWidth: 2,
          shadowColor: 'rgba(91, 140, 255, 0.11)',
          shadowBlur: 22,
          shadowOffsetX: 0,
          shadowOffsetY: 6,
      },
      tooltip: {// 这个有可能移动到白色的圆环上,上层的圆环的tooltip会展示出来,这里需要禁掉
          show: false
      }
      ...
}]

4、对饼状图的记录2

截屏2022-11-04 15.04.47.png

 let chartDom = document.getElementById(this.props.id);
        this.myChart = echarts.init(chartDom);
        let option;
        let data = [            { value: 1048, name: '紧急' },            { value: 735, name: '异常' },            { value: 580, name: '提醒' }        ];
        // legend 格式化
        const legendPercent = (name) => {
            let findData = data.find((item) => item.name === name);
            return '{nameC|' + name + '}{valueC|' + findData.value + '}';
        };
        option = {
            tooltip: {
                trigger: 'item'
            },
            title: {
                text: this.props.chartTitle,// 饼图的名称
                textStyle: {
                    color: 'rgba(0, 0, 0, 0.85)',
                    fontSize: 16,
                    fontWeight: 400,
                    lineHeight: 16
                },
            },
            // *_2_* 在这里自定义圆环中间的字体,鼠标移动到这里的时候不会有tooltip
            // title: {
                // text: sum,// 饼图的名称
                // subtext: sumLabel,
                // ...titleStyle,
                // textAlign: 'center',
                // itemGap: 0,
                // top: 100,
                // left: '39%', // 使用百分比可以确保中间的字体能在饼图中间
                // textVerticalAlign: 'center',
                // textStyle: {
                    // color: 'rgba(0, 0, 0, 0.75)',
                    // fontSize: 30,
                // },
                // subtextStyle: {
                    // fontSize: 14,
                    // color: '#8c8c8c',
                    // fontWeight: 300,
                    // opacity: 0.25,
                // },
            // },
            legend: {
                ...this.props.legend,
                itemWidth: 4,
                itemHeight: 10,
                orient: 'vertical',
                data: ['紧急', '异常', '提醒'],
                formatter: legendPercent,
                textStyle: {
                    rich: {
                        nameC: {
                            ellipsis: 'truncate',
                            color: '#595959',
                        },
                        valueC: {
                            padding: this.props.legendItemPadding,
                            color: '#8C8C8C'
                        }
                    }
                }
            },
            color: this.props.color,
            series: [
                {
                    name: 'Access From',
                    type: 'pie',
                    top: -40,
                    center: ['50%', '50%'], // 使用百分比可以确保饼图在水平的中间
                    radius: this.props.seriesRadius || ['50%','60%'],
                    avoidLabelOverlap: false,
                    label: {
                        show: false,
                        position: 'center'
                    },
                    tooltip: {// tooltip 提示框的样式
                        padding: 5,
                        borderWidth: 0,
                        borderColor: null,
                        backgroundColor: '#fff',
                        trigger: 'item',
                        extraCssText: 'background: #FFFFFF;box-shadow: 0px 2px 12px 0px rgba(179, 179, 179, 0.40);padding: 4px 2px', // 额外附加到浮层的 css 样式
                        formatter: function (params) {
                        // *_3_* 如果需要环形中间的文字也有提示的话,就在这里从params里面取想要的数据,结合方式一(*-1-*)来写的
                            let html =
                                '<div style="font-size: 13px;font-family: MicrosoftYaHei;box-shadow: 0px 2px 12px 0px rgba(179, 179, 179, 0.40);">'
                                + '<span' +
                                ' style="display:inline-block;line-height: 17px;margin-left:10px;width:4px;height:10px;margin-right: 6px;'
                                + 'background-color:' + params.color + '"></span>'
                                + '<span style="display:inline-block;margin-right: 12px;line-height: 17px;color:#595959;">'
                                + params.name + '</span>'
                                + '<span  style="display:inline-block;line-height: 17px;color: #8C8C8C;margin-right: 10px;">' + params.value + '</span>'
                                + '</div>'
                            return html
                        }
                    },
                    emphasis: {// 饼图正中间的字
                    // *-1-*  这种写法有一个问题:鼠标移动到中间的时候,tooltip提示框会展示其他的数据,不是中间自定义的数据
                        label: {
                            show: true,
                            align: 'center',
                            formatter: function (params) {
                                return '{totalNum|' + 123224 + '}' + "\n" + '{name|' + "总计" + '}';
                            },
                            rich: {
                                totalNum: {
                                    color: 'rgba(0, 0, 0, 0.65)',
                                    lineHeight: 20,
                                    fontSize: 30,
                                    fontWeight: 'bold',
                                    marginBottom: "5px"
                                },
                                name: {
                                    fontSize: 14,
                                    color: 'rgba(0, 0, 0, 0.65)',
                                    lineHeight: 20,
                                },

                            }
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: data
                }
            ]
        };

        option && this.myChart.setOption(option);
        // 这里监听图表的父级的宽度做到自适应宽度
        window.addEventListener("resize", () => {
            this.myChart.resize();
        });

6、对横坐标刻度名称的省略和鼠标移动到刻度名展示全称

image.png

const HistogramChart = (
    title,
    data,
    id,
    lineColor,
    bgColor,
    lineLabel,
    style,
    clickPie,
    type,
}) => {

const watchWindowSize = () => {
    let charDom = document.getElementById(id);
    echarts.init(charDom).resize();
};

useEffect(() => {
    let charDom = document.getElementById(id);
    let myChart = echarts.init(charDom);
    const option = {
        title: {
        text: title,
        textStyle: {
            color: 'rgba(0, 0, 0, 0.85)',
            fontSize: 14,
            fontWeight: 400,
            lineHeight: 16,
        },
    },
    grid: {
        top: '10%',
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
    },
    xAxis: {
        type: 'category',
        // boundaryGap: false,
        data: data.chart.labels,
        axisLine: {
            lineStyle: {
                color: '#aaa',
            },
        },

        axisLabel: {
            interval: 0,
            rotate: 20,
            formatter: (value) => {
                // *-^-* 重点2
                // 刻度名省略
                return value.length > 7 ? value.slice(0, 5) + '...' : value;
            },
        },
        triggerEvent: true, // *-^-* 重点1 设置为true的时候,鼠标移动到刻度显得名称时才会展示全称
    },

    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow',
        },
    },
    yAxis: {
        type: 'value',
        axisLine: {
            lineStyle: {
                color: '#aaa',
            },
        },
        splitNumber: 5,
    },
    series: [
    {
        data: data.chart.data,
        type: 'bar',
        barWidth: 20,
        itemStyle: { color: '#FF7874' },
    },
    ],
};

// *-^-* 重点3
const extension = (chart, id) => {
    // 注意这里,是以X轴显示内容过长为例,如果是x轴的话,需要把params.componentType == 'xAxis'改为yAxis
    // 判断是否创建过div框,如果创建过就不再创建了
    // 该div用来盛放文本显示内容的,方便对其悬浮位置进行处理

    var element = document.getElementById('extension');
    if (!element) {
        var div = document.createElement('div');
        div.setAttribute('id', 'extension');
        console.log(`div`, div);
        div.style.display = 'block';
        document.querySelector(`#${id}`).appendChild(div);
    }

    chart.on('mouseover', function (params) {
    console.log(`params`, params);
    if (params.componentType === 'xAxis') {
    var elementDiv = document.querySelector('#extension');
    console.log(`elementDiv`, elementDiv);
    //设置悬浮文本的位置以及样式
    var elementStyle =
    'position: absolute;z-index: 99999;color: #fff;font-size: 12px;padding: 5px;display: inline;border-radius: 4px;background-color: #303133;box-shadow: rgba(0, 0, 0, 0.3) 2px 2px 8px';
    elementDiv.style.cssText = elementStyle;
    elementDiv.innerHTML = params.value;
    document.querySelector(`#${id}`).onmousemove = function (event) {
        var elementDiv = document.querySelector('#extension');
        console.log(`event`, event);
        var xx = event.zrX - 10;
        var yy = event.zrY + 15;
        console.log('xx', xx);
        console.log(`yy`, yy);
        elementDiv.style.top = yy + 'px';
        elementDiv.style.left = xx + 'px';
    };
    }
    });
    chart.on('mouseout', function (params) {
        //注意这里,我是以X轴显示内容过长为例,如果是y轴的话,需要改为yAxis
        if (params.componentType === 'xAxis') {
            var elementDiv = document.querySelector('#extension');
            elementDiv.style.cssText = 'display:none';
        }
    });

};

    myChart.off('click');
    myChart.on('click', (param) => {
        clickPie && clickPie(type, param.name, param.dataIndex);
    });
    option && myChart.setOption(option);
    // *-^-* 重点4
    extension(myChart, id);
}, [data]);

useEffect(() => {
    window.addEventListener('resize', watchWindowSize);
    return () => {
        window.removeEventListener('resize', watchWindowSize);
    };
}, []);
return <div id={id} style={style} />;
};
export default HistogramChart;

7、对进度条的记录

这里用的是html中的<progress>标签实现的进度条,没有用到Echarts

截屏2022-04-24 下午4.35.27.png

<div className={css.chart}>
    {data.length > 0 &&
      data.map((item, index) => {
        return (
          <div key={index} className={css.progressItem}>
            <div className={css.proTopLabel}>
              <p className={css.left}>
                <span
                  style={{
                    backgroundColor: index > 3 ? topList[3] : topList[index],
                  }}
                >
                  {index + 1}
                </span>
                {item.name}
              </p>
              <p className={css.right}>{item.count}</p>
            </div>
            <progress
              value={item.count}
              max={data[0].value}
              width="100%"
            ></progress>
          </div>
        );
      })}
</div>

对应的css记录

/* 隐藏滚动条, */
.chart::-webkit-scrollbar {
  display: none;
}
.chart {
  background: #ffffff;
  overflow-y: scroll;
  border-radius: 4px;
  width: 100%;
  height: 540px;
  padding: 32px 24px;
}
.progressItem {
  margin-bottom: 26px;
}
.proTopLabel {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 6px;
}
.left {
  font-size: 14px;
  color: #262626;
}
.left span {
  display: inline-block;
  text-align: center;
  font-size: 12px;
  color: #ffffff;
  width: 18px;
  margin-right: 14px;
  font-weight: bold;
  height: 18px;
  border-radius: 50%;
}
.right {
  font-size: 13px;
  color: #8c8c8c;
}
progress {
  width: calc(100% - 32px);
  height: 5px;
  margin-left: 32px;
  border-radius: 1em;
  overflow: hidden;
  background-color: rgba(0, 0, 0, 0.06);
  color: #6974a6;
}
/*表示在Firefox下已完成进度的颜色*/
progress::-moz-progress-bar {
  background: #6974a6;
}
/*表示在chrome下全部进度的颜色*/
progress::-webkit-progress-bar {
  background: rgba(0, 0, 0, 0.06);
}
/*表示在chrome下已完成进度的颜色*/
progress::-webkit-progress-value {
  background: #6974a6;
}

8、双进度条

封装的组件,记录一下!但是和echarts没啥关系!

双进度条.png

// 使用
<TwoProgress
    leftLabel="合规节点:"
    leftNum={data['compliance_node'] || 0}
    leftPercent={data['compliance_rate'] || 0}
    rightLabel="不合规节点:"
    rightNum={data['non_compliance_node'] || 0}
    rightPercent={data['non_compliance_rate'] || 0}
    width="100%" 
/>

// TwoProgress主要的代码
 const percentFun = () => {
        if (leftNum === 0 && rightNum === 0) {
            return (
                <div
                    style={{
                        display: 'flex',
                        justifyContent: 'center',
                        height: '6px',

                    }}
                >
                    <Tooltip title="暂无数据">
                        <div
                            style={{
                                background: '#E8E8E8',
                                width: width,
                                borderRadius: '3px',
                                cursor: 'pointer',
                                height: '6px',
                            }}
                        />
                    </Tooltip>
                </div>

            );
        } else if (rightNum === 0) {
            return (
                <div
                    style={{
                        display: 'flex',
                        justifyContent: 'center',
                        height: '6px',
                    }}
                >
                    <Tooltip title="合规节点:100%">
                        <div
                            style={{
                                background: '#F5222D',
                                width: width,
                                borderRadius: '3px',
                                cursor: 'pointer',
                                height: '6px',
                            }}
                        />
                    </Tooltip>
                </div>

            );
        } else if (leftNum === 0) {
            return (
                <div
                    style={{
                        display: 'flex',
                        justifyContent: 'center',
                        height: '6px',
                    }}
                >
                    <Tooltip title="不合规节点:100%">
                        <div
                            style={{
                                background: '#FF7875',
                                width: width,
                                borderRadius: '3px',
                                cursor: 'pointer',
                                height: '6px',
                            }}
                        />
                    </Tooltip>
                </div>
            );
        } else {
            return (
                <div
                    style={{
                        display: 'flex',
                        justifyContent: 'center',
                        height: '6px',
                        // width: '100%',
                    }}
                >
                    <Tooltip title={'合规节点:' + leftPercent + '%'}>
                        <div
                            style={{

                                background: '#3BB7FF',
                                width: leftPercent * width + 'px',
                                borderRadius: '3px 0 0 3px',
                                cursor: 'pointer',
                            }}
                        />
                    </Tooltip>
                    <Tooltip title={'不合规节点:' + rightPercent + '%'}>
                        <div
                            style={{
                                background: '#FF7875',
                                width: rightPercent * width + 'px',
                                borderRadius: '0 3px 3px 0',
                                cursor: 'pointer',
                            }}
                        />
                    </Tooltip>
                </div>
            )
        }
    }
    
    return (
        <div className="twoProgress">
            <div className="twoProgress-label">
                <p>{leftLabel}{leftNum}</p>
                <p>{rightLabel}{rightNum}</p>
            </div>
            <div className="twoProgress-progress">
                {percentFun()}
            </div>
        </div>
    )