Echarts 图表开发遇到的问题与总结

Echarts 图表开发遇到的问题与总结

1.安装导入

import * as echarts from 'echarts';

2.dom引用

    <div style="width: 100%; height: 343px;" ref="chartDom" v-loading="isLoading"> </div>

3.基本使用:arrow_down:

3.1 bar 图——按时间展示人数和占比

  • 📈没有数据是no data 设置
  • tooltip 自定义设置
  • 坐标轴线和label自定义设置
const chartDom = ref();

const colors = ['#EC4586', '#2675FF'];

const initChart = (): void => {
    if (chartDom.value && chartDom.value.dispose) {
        // 移去上次渲染的结果,确保本次不受影响
        chartDom.value.dispose();
    }
    const chart = chartDom.value && echarts.init(chartDom.value)
    
    // 指定图表的配置项和数据
    const option: any = {
        color: colors,
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
            },
         // 指定图表的配置项和数据
    const option: any = {
        color: colors,
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
            },
        },

        grid: {
            right: '20%', // margin-right 图边距
        },
        xAxis: [
            {
                type: 'category', 
                // prettier-ignore
                data: XData.value,// 这里x轴就是后端返回的日期
                axisTick: {
                    show: false,
                    gridIndex: 0,
                },

                axisLine: {
                    lineStyle: { // 设置x 轴颜色
                        color: '#ebedf0',
                    },
                },
                axisLabel: {
                    // x轴文字样式设置
                    show: true,
                    textStyle: {
                        color: '#898a8c',
                        fontSize: '12px',
                        fontFamily: ' Roboto, Roboto-Regular',
                        fontWeight: 400,
                        textAlign: 'CENTER',
                    },
                },
            },
        ],
      
           yAxis: [
                {
                    type: 'value',
                    name: '活跃人数',
                    position: 'left',
                    // alignTicks: true,
                },
                {
                    type: 'value',
                    name: '活跃率',
                    position: 'right',
                    // alignTicks: true,
                    offset: 80,
                    axisLabel: {
                        formatter: '{value} %', // 自定义展示y轴标签
                    },
                },
            ],
          series: [
                {
                    name: chartTitle.activeDayCnt,
                    type: 'bar',// 此处为bar图
                    yAxisIndex: 0,
                    data: y1,
                    barWidth: 16,// 可自定义设置barwidth
                },
                {
                    name: chartTitle.activeDayRate,
                    type: 'bar',
                    yAxisIndex: 1,
                    data: y2,
                    barWidth: 16
                },
            ],
    };
    // 当数据为空的时候,在图标中间展示“no data” 
    if (XData.value.length === 0) {
        const optionEmpty = {
            title: {
                text: 'No data',
                x: 'center',
                y: 'center',
                textStyle: {
                    fontFamily: 'Roboto, Roboto-Regular',
                    color: '#ccc',
                    fontWeight: 'normal',
                    fontSize: 16,
                },
            },
        };
        // option 重新渲染 
        chart.setOption(optionEmpty, true);
    } else {
        XData.value.length && chart.setOption(option, true); // 设置true 及时刷新
    }
  
  // 请求后端数据处理        
 const getTrend = async (): Promise<void> => {
    try {
        isLoading.value = true;

        const data = await fetchTrendDiagram(searchForm.value);
        XData.value = data.map((item: any) => dayjs(item.pDate).format('YYYY-MM'));// X 轴数据
        chartsData.value = data;
      // y轴数据
         chartsData.value?.forEach((item: any) => { 
            y1.push(item.activeDayCnt);
            y2.push(item.activeDayRate);
        });
        initChart(); // 触发echarts
    } catch (e) {
        Message.error(e);
    } finally {
        isLoading.value = false;
    }
};

其中tooltip自定义配置:

  1. 根据数据判断是否展示%:
 formatter: function (param: any): string {
                return `
                    <div style="padding: 12px; line-height: 25px;font-size: 14px;font-family: Roboto, Roboto-Regular;
                        font-weight: 400;text-align: LEFT;color: #252626;">
                        ${param[0].axisValue}</br>
                        ${param
                            .map((item: any) => {
                                let str = '';
                                if ( item.seriesName ==="活跃率"     
                                ) {
                                    str += `
                                    ${item.marker} ${item.seriesName}:${item.data}%
                                `;
                                } else {
                                    str = `
                                ${item.marker} ${item.seriesName}:${item.data}
                            `;
                                }
                                return str;
                            })
                            .join('<br>')}
                    </div>
                `;
            },
2. 使用三元表达式条件设置tooltip 中的样式
 formatter: function (param: any): string {
                return `
                    <div style="padding: 12px; line-height: 25px;font-size: 14px;font-family: Roboto, Roboto-Regular;
                        font-weight: 400;text-align: LEFT;color: #252626;">
                        ${param[0].axisValue}</br>
                        ${param
                            .map((item: any) => {
                                let str = '';

                                // 使用三元表达式条件设置样式

                                str = `
                                ${item.marker}视频数:<span style="font-size: 14px; ${item.data.videoStatus ? 'color:#FF4940;' : 'color: #005cff'
                                }" > ${item.data.video}${t('days')} </span>
                                </br> 
                            `;
                                return str;
                            })
                            .join('<br>')}
                    </div>
                `;
            },
3. 在toolip中加入点击事件
 formatter: function (param: any): string {
                        let str;
                        // 节点hover自定义内容
                        
                            // * 字符串里写事件,不能使用onclick,注意参数拼接方式, 目前不使用这个事件(需要在window.test 方式注册)
                            str =
                                ` <span  onclick="test(\'` +
                                JSON.stringify(param.data).replace(/"/g, '&quot;') +
                                `\')"  
                                style="font-size: 14px; font-family: Roboto, Roboto-Regular; font-weight: 400; color: #333;"> 
                                ${param.data.source} -- ${param.data.target}
                                 <span style="font-weight: 500;color: #1f1f1f;">
                                 ${param.value}%  ${param.data.num}</span></span>`;
                        return str;
                    },
                      
  
                     
 window.test = function(param){
    console.log(param)
}              

3.2 sangkey 图

记录一些自定义的配置,主要是series:

 series: {
                    type: 'sankey',
                    layout: 'none',
                    emphasis: {
                        focus: 'adjacency',
                    },

                    lineStyle: {
                        color: 'gradient',
                        curveness: 0.5,
                    },
                    // 对节点标签样式单独设置
                    label: {
                        fontSize: 12,
                        color: '#666',
                        formatter: function (params: any): any {
                            const { data } = params;
                            return `${data.name} ${data.value}% ${data.size}`;
                        },
                    },

                    left: '10%', // 图边距
                    right: '10%',
                    height: '90%', //  设置的高度 100% 可能会覆盖部分数据
                    nodeGap: 20, // name 节点间距
                    data: sankeyNodeName.value,
                    links: sankeyNodeLink.value,
                    layoutIterations: 0, // *布局迭代次数,设置为0 可让data按指定顺序展示
                },

3.3 折线图

主要📝记录:

  • 折线的渐变效果

    const color = ['#005CFF', '#1AC7B5', '#9E9E9E', '#FFA442', '#FF4940'];//定义一组颜色 
        // 指定图表的配置项和数据
        const option: any = {
          // 利用该属性根据data的value值设置渐变的范围,
            visualMap: [ 
                {
                    show: false,
                    type: 'continuous',
                    seriesIndex: 0,
                    min: -20,// 图表数据的最值
                    max: 30,
                    target: {
                        inRange: {
                            color: color.reverse(),
                        },
                    },
                },
            ],
        ...
        }
          
    
  • 折线图y轴一般是数值,这里需要设置为文本表示类型,但是又需要有在x 轴下方的表示,因此不能直接设置category 属性。value 为折线图对应的数据。

     yAxis: [
                {
                    type: 'value', // 不设置category
                    axisLabel: {
                        formatter: function (value): any {
                            const texts: any = [];
                            if (value == 0) {
                                texts.push('未上学');
                            } else if (value == 10) {
                                texts.push('小学');
                            } else if (value == 20) {
                                texts.push('中学');
                            } else if (value == 30) {
                                texts.push('大学');
                            } else if (value == -10) {
                                texts.push('中专');
                            } else if (value == -20) {
                                texts.push('劝退');
                            }
                            return texts;
                        },
                  }
              ]
         
    
  • 设置折线下方颜色渐变效果

    
    series:[
                      {
                            name: '总数',
                            yAxisIndex: 0,
                            data: y1,
                            color: '#005CFF',
                          type: 'line',
                smooth: true,
                symbol: 'circle',
                showSymbol: false, // hover 时展示symbol
                symbolSize: 6,
                            areaStyle:    {
                    opacity: 0.12,
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: '#005CFF',
                        },
                        {
                            offset: 1,
                            color: '#fff',
                        },
                    ]),
                };
                        },
                      
    ]                 
    
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容