FlotChart - 如何为折线图中的特定系列分配颜色?

FlotChart - how to assign a color to a particular series in a linechart?

我使用 flotcharts JS 折线图来显示不同股票交易头寸的价值。用户可以 show/hide 通过图表上方的复选框在图表上进行每笔交易。 默认情况下,折线图按照创建系列的顺序使用我的默认或预定义颜色。所以第一行得到颜色 1,第二行得到颜色 2 等等。 这对于这种情况不是很好,因为当用户隐藏交易一的线时,之前的交易二变成新的 "first line" 并且它的颜色也从颜色 2 更改为颜色 1。 由于该行表示的数据仍然相同,因此这种行为非常令人恼火。 为了解决这个问题,我想通过它的名称、id 或类似的而不是它在图表上创建的顺序为一个系列分配颜色,因为这个标识符即使在 adding/removing 图表中的其他行之后也保持不变.

我该怎么做?

目前我使用这样的代码来设置第一行、第二行等的颜色。

var datatoprint=[];
for(var key in arrTradeSymbols){
    if (arrTradeSymbols[key].visible==true){
        datatoprint.push(arrTradeSymbols[key].data);
        jQuery("#symb_"+arrTradeSymbols[key].tradeid).prop("checked",true);
    }
}

var plot = $.plot(jQuery("#kt_flotcharts_pl"), datatoprint, {
legend: {
      position: "nw",
    },
    series: {
        lines: {
            show: true,
            lineWidth: 2,
            fill: false,
        },
        points: {
            show: true,
            radius: 3,
            lineWidth: 1,
            color: '#00ff00'
        },
        shadowSize: 2
    },
    grid: {
        hoverable: true,
        clickable: true,
        tickColor: "#eee",
        borderColor: "#eee",
        borderWidth: 1
    },
    colors: ['#0083d0', '#1dc9b7'],
    xaxis: {
        mode: "time",
        tickSize: [5, "day"],
        tickLength: 0,
        tickColor: "#eee",
    },
    yaxis: {
        ticks: 11,
        tickDecimals: 0,
        tickColor: "#eee",
    }
});

这很简单:只需提供具有颜色的对象数组以及数据,而不是仅将数据作为数组提供。

示例片段:

var arrTradeSymbols = {
  trade1: {
    color: "red",
    data: [
      [1, 3],
      [2, 4],
      [3.5, 3.14]
    ]
  },
  trade2: {
    color: "green",
    data: [
      [1, 4],
      [2, 11.01],
      [3.5, 5.14]
    ]
  }
};

function run() {
  var datatoprint = [];
  for (var key in arrTradeSymbols) {
    if ($("#" + key).is(":checked")) {
      datatoprint.push(arrTradeSymbols[key]);
    }
  }

  $.plot($("#kt_flotcharts_pl"), datatoprint, {
    legend: {
      position: "nw",
    },
    series: {
      lines: {
        show: true,
        lineWidth: 2,
        fill: false
      },
      points: {
        show: true,
        radius: 3,
        lineWidth: 1
      },
      shadowSize: 2
    },
    grid: {
      hoverable: true,
      clickable: true,
      tickColor: "#eee",
      borderColor: "#eee",
      borderWidth: 1
    },
    xaxis: {
      ticks: 5
    },
    yaxis: {
      ticks: 11,
      tickDecimals: 0,
      tickColor: "#eee",
    }
  });
}

run();

$("input").on("input", run);
#kt_flotcharts_pl {
  width: 400px;
  height: 200px;
  border: 1px solid black;
}
label {
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.2/jquery.flot.min.js"></script>


<label><input type="checkbox" id="trade1" checked> Red</label>
<label><input type="checkbox" id="trade2" checked> Green</label>
<div id="kt_flotcharts_pl"></div>