echarts custom legend

Posted May 28, 20202 min read

<! DOCTYPE html>



ECharts
<!-Introduce echarts.js->




<!-Prepare a Dom with size(width and height) for ECharts->

      <div style = "position:absolute; left:50%; transform:translateX(-50%); z-index:10;">
        <button
          style = "height:28px;"
          onclick = "onLegendClick('Mail Marketing')"
        >
          Email marketing
        </button>
        <button
          style = "height:28px;"
          onclick = "onLegendClick('Affiliate Advertising')"
        >
          Affiliate ads
        </button>

      </div>

      <div id = "main" style = "width:100%; height:100%"> </div>
    </div>
    <script type = "text/javascript">
      //Initialize the echarts instance based on the prepared dom
      var myChart = echarts.init(document.getElementById("main"));

      //Specify the configuration items and data of the chart
      var option = {
        title:{
          text:"Line chart stacking"
        },
        tooltip:{
          trigger:"axis"
        },
        legend:{
          show:false,
        },
        grid:{
          left:"3%",
          right:"4%",
          bottom:"3%",
          containLabel:true
        },
        xAxis:{
          type:"category",
          boundaryGap:false,
          data:["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
        },
        yAxis:{
          type:"value"
        },
        series:[
          {
            name:"Mail Marketing",
            type:"line",
            stack:"Total",
            data:[120, 132, 101, 134, 90, 230, 210]
          },
          {
            name:"Affiliate Advertising",
            type:"line",
            stack:"Total",
            data:[220, 182, 191, 234, 290, 330, 310]
          },
          {
            name:"Video Advertising",
            type:"line",
            stack:"Total",
            data:[150, 232, 201, 154, 190, 330, 410]
          },
          {
            name:"Direct Access",
            type:"line",
            stack:"Total",
            data:[320, 332, 301, 334, 390, 330, 320]
          },
          {
            name:"Search Engine",
            type:"line",
            stack:"Total",
            data:[820, 932, 901, 934, 1290, 1330, 1320]
          }
       ]
      };

      //Use the configuration item and data just specified to display the chart.
      myChart.setOption(option);

      var onLegendClick = function(name) {
        myChart.dispatchAction({
          type:"legendToggleSelect",
          //Legend name
          name:name,
        });
      };
    </script>
  </body>
</html>