javascripthtmlecharts

In ECHARTS how to start with a hidden serie and then make it visible with custom legend


How start with a hidden serie on graph and then display it with a custom legend button like

<div>
  <input type="button" value="hide show NAME_OF_THE_SERIE" id="buttonid">
</div>

<script>
button = document.body.querySelector('#buttonid');
button.addEventListener('click', (e) => {   
    myChart.dispatchAction({
      type: "legendToggleSelect",
      name: "NAME_OF_THE_SERIE"
    });
    console.log(myChart.getOption().series);
});
</script>

Here the link of the codepen.io where I took this

Now, like you see in console (if you implement this method) the object with the serie name "NAME_OF_THE_SERIE" returned with chart.getOption().series it's exactly the same when the serie is hidden and when it's showed on graph.

So also how to know if a serie it's hidden?


Solution

  • You can use the legend.selected setting to hide/show specific series by default or to modify their visibility status in response to an external event.

    const option = {
      legend: {
        selected: {
          // serieName: true (show) / false (hide)
          serieName: false,
        },
      },
    };
    

    /**
     ** Initialize
     */
    const chartDom = document.getElementById('chart');
    const chart = echarts.init(chartDom);
    
    /**
     ** Data
     */
    const categoryData = ['category0', 'category1', 'category2', 'category3', 'category4'];
    const barData = [30, 50, 70, 60, 80];
    
    /**
     ** Option
     */
    const option = {
      legend: {
        selected: {
          // serieName: true (show) / false (hide)
          serieName: false,
        },
      },
      yAxis: {},
      xAxis: {
        type: 'category',
        data: categoryData,
      },
      series: [
        {
          type: 'bar',
          name: 'serieName',
          data: barData,
        },
      ]
    };
    
    /**
     ** Render Chart
     */
    chart.setOption(option);
    
    /**
     ** Change series legend selected status by external function
     */
    document.getElementById('toggleVisibility').addEventListener('click', () => {
      const legendSelected = option.legend.selected['serieName'];
      option.legend.selected['serieName'] = ! legendSelected;
      chart.setOption(option, true);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.5.0/echarts.min.js" integrity="sha512-k37wQcV4v2h6jgYf5IUz1MoSKPpDs630XGSmCaCCOXxy2awgAWKHGZWr9nMyGgk3IOxA1NxdkN8r1JHgkUtMoQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    
    <button id="toggleVisibility">Toggle legend visibility</button>
    
    <div id="chart" style="width: 650px; height: 250px;"></div>