ChartJS 如何用同一标签管理线、散点图?

iqxoj9l9  于 2023-03-08  发布在  Chart.js
关注(0)|答案(1)|浏览(158)

我是React图2的新手

这是我的情节。有相同的标签,如因子5因子5因子6因子6...
我想做的是同时打开/关闭绘图。当我禁用因子5时,那么点和线将被禁用。但现在我必须彼此点击。
我该怎么办?这是我的密码。

function createChart4() {

    let result = Object.assign([], resultScatter);
    let result2 = Object.assign([], resultData);
    let columns = Object.keys(resultScatter[0]).filter(el => el !== "Y");
    const colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#17becf"
                    "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22"];
    let x=[];
    for (let i=0; i<columns.length; i++){
          x[i] = result.map((data) => data[columns[i]]);
        }
    let y = result.map((data) => data.Y);
    let scatterData = {
        datasets:[],
      };
    for (let i = 0; i < columns.length; i++) {
      let color = colors[i];
      let label = columns[i];
      let lines = result2.filter(el => el.FACTOR_CD === transLangKey(columns[i]))[0];
      let minX = Math.min(...x[i]);
      let maxX = Math.max(...x[i]);
    
      scatterData.datasets.push({
        label: label,
        data: x[i].map((val, index) => ({x: val, y: y[index]})),
        backgroundColor: color,
        borderColor: color,
        hidden: i !== 0,
        showLine: false,
        },
        {
        label: label,
        showLine: true,
        data: [{x: minX, y: lines.REG_COEF * minX + lines.CONSTANT},
               {x: maxX*1.05, y: lines.REG_COEF * maxX*1.05 + lines.CONSTANT},
               ],
        backgroundColor: color,
        borderColor: color,
        hidden: i !== 0,
        });
      }
      setChart4Data(scatterData);
    }

当我点击一个标签,点和线被禁用或可视化在同一时间。

7fyelxc5

7fyelxc51#

setChartPlugin({
    title: {
      display: false
    },
    legend: {
      labels: {
        filter: function(legendItem, chartData) {
          if (legendItem.datasetIndex === 0) {
            return true;
          }
          return false;
        }
      },
      onClick: function(e, legendItem, legend){
         const index = legendItem.datasetIndex;
         const ci = legend.chart;
         if (ci.isDatasetVisible(index)) {
           ci.hide(index);
           ci.hide(index+1);
           legendItem.hidden = true;
         } else {
           ci.show(index);
           ci.show(index+1);
           legendItem.hidden = false;
         }
      }
    },
  });

在图表插件中添加此代码块。它工作。

相关问题