Search code examples
javascriptchartsecharts

Is there a way to have Custom legends to toggle lines in Echarts


I am developing a multi chart layout using echarts library. All the charts have same legends but different dataset.

Is there way to make custom legend sections in echarts using which I can handle all the charts at once ?

I have tried toggling "show" property of each series and also "visible" property but all the do is hide the data points on chart not the complete series.


Solution

  • You can add a shared legend and use it in all of your charts

    const legend = {
        type: 'scroll',
        orient: 'vertical',
        right: 10,
        top: 20,
        bottom: 20,
        data: ['Legend A', 'Legend B', 'Legend C' /* ... */, , 'Legend x']
        // ...
      }
    
    // chart 1
    const chart1 = echarts.init(dom1)
    chart1.setOption({
        legend,
        dataset: {
          source: [
            // ...
          ]
        },
        // other settings...
      },
    })
    
    // chart 2
    const chart2 = echarts.init(dom2)
    chart2.setOption({
        legend,
        dataset: {
          source: [
            // ...
          ]
        },
        // other settings...
      },
    })
    
    

    or you can wrap in your own function

    function createEchartOption(dataset){
      return {
        dataset,
        legend: {
        type: 'scroll',
        orient: 'vertical',
        right: 10,
        top: 20,
        bottom: 20,
        data: ['Legend A', 'Legend B', 'Legend C' /* ... */, , 'Legend x']
        // ...
      },
      // other settings...
    }
    
    const chart = echarts.init(dom)
    chart.setOption(createEchartOption({...}))