Search code examples
jqueryflotlinechart

Flot multi line chart with categories not showing labels


I am trying to render multi-line charts using flot js. I would like to show x-axis with customized text with the label in chart end-points. Here is my js fiddle link.

  var labelArray1 = ["0.35%", "0.34%", "0.45%", "0.77%", "1.07%"];
  var d1 = [["2018-Jan", 0.35], ["2018-Feb", 0.34], ["2018-Mar", 0.45], ["2018-Apr", 0.77],["2018-May", 1.07]];

  var labelArray2 =["0.53 kegs", "0.62 kegs", "0.85 kegs", "1.04 kegs", "1.06 kegs"];
  var d2 = [["2018-Jan", 0.53], ["2018-Feb", 0.62], ["2018-Mar", 0.85], ["2018-Apr", 1.04],["2018-May", 1.06]];

  var data = [ { data: d1, cColor: "orange", canvasRender: true, dashes: {show: true}, showLabels: true,points: {show: true}, label: "section1", labelPlacement: "above", labels: labelArray1  }, { data: d2, lines: {show: true}, points: {show: true}, cColor: "AD8200", canvasRender: true, label: "section2", labelPlacement: "above", labels: labelArray2,  showLabels: true }];
  var options = {legend:{position:"nw"}, grid: { hoverable: true },xaxis: { autoscaleMargin: 0.04, fillStyle: "#000", mode: "categories", rotateTicks: "90",  font: { color: "#000" } }, yaxis: {ticks:[]}};     

  $(document).ready(function(){
    chart = $.plot($("#placeholder"),data,options);
  });

I am using the following plugins: flot-dashes, flot-labels, flot-categories

When I use the categories plugin the label is not displaying in the lines chart.


Solution

  • The problem is, that the labels plugin tries to get the position of the points at ["2018-Jan", ...] from the plot.pointOffset() function, but that can only calculate the position if it gets a numberic value. You can solve this by not using the categories plugin and implementing categories mode yourself. For that change the data to

    var d1 = [
        [0, 0.35],
        [1, 0.34],
        [2, 0.45],
        [3, 0.77],
        [4, 1.07]
    ];
    

    and give a ticks array for the xaxis in the options:

    ticks: [[0, "2018-Jan"], [1, "2018-Feb"], [2, "2018-Mar"], [3, "2018-Apr"], [4, "2018-May"]]
    

    See this updated fiddle for a full working example.