如果在flot图表中特定x轴中不存在数据时如何设置默认y轴值

时间:2014-10-02 17:27:37

标签: javascript charts flot

enter image description here我使用数据点生成了一个flot图表。我没有使用刻度线表示x和y轴。原因是我的数据集会变化很大。

现在flot chart生成图表。但是当没有数据时,它会在刻度线之间中断。 如果没有数据,如何设置默认的y轴值?

1 个答案:

答案 0 :(得分:2)

当您的现有数据点相隔超过一天时,您必须在现有数据点之间插入零值的数据点。我为此创建了这个函数:

function prepareData(data) {
    if (data && data.length > 0) {
        var oneDay = 86400000;
        var newData = [];

        // new zero value point before the old first point
        newData.push([(parseInt(data[0][0], 10) - oneDay).toString(), "0"]);

        for (var i = 0; i < data.length; i++) {
            // add existing point to new data
            newData.push(data[i]);

            // check distance between this point and the next (if not last point)
            if (i < data.length - 1) {
                var thisPointTimestamp = parseInt(data[i][0], 10);
                var nextPointTimestamp = parseInt(data[i + 1][0], 10);

                // if distance is two days, insert ony zero value point in between
                if (nextPointTimestamp - thisPointTimestamp == 2 * oneDay) {
                    newData.push([(thisPointTimestamp + oneDay).toString(), "0"]);
                }
                // if distance is more than two days, insert one zero value point
                // directly after this day and one directly before the next day
                else if (nextPointTimestamp - thisPointTimestamp > 2 * oneDay) {
                    newData.push([(thisPointTimestamp + oneDay).toString(), "0"]);
                    newData.push([(nextPointTimestamp - oneDay).toString(), "0"]);
                }
            }
        }

        // new zero value point after the old last point
        newData.push([(parseInt(data[data.length - 1][0], 10) + oneDay).toString(), "0"]);

        return newData;
    }
}

有关完整示例,请参阅此更新的fiddle。或者这段代码:

	var responseCountData, datasets;

	function displayGraph() {

	  responseCountData = response = {
	    "alertCount": {
	      "RED": [
	        ["1397433600000", "1"],
	        ["1397520000000", "2"],
	        ["1400457600000", "1"],
	        ["1400544000000", "5"],
	        ["1401148800000", "1"],
	        ["1407456000000", "1"],
	        ["1407715200000", "1"],
	        ["1408406400000", "1"],
	        ["1408492800000", "1"],
	        ["1409097600000", "3"],
	        ["1409097600000", "4"],
	        ["1409097600000", "2"],
	        ["1409184000000", "1"],
	        ["1409184000000", "1"],
	        ["1409184000000", "1"],
	        ["1409270400000", "4"],
	        ["1409270400000", "2"]
	      ],
	      "YELLOW": [
	        ["1397433600000", "2"],
	        ["1397433600000", "1"],
	        ["1397520000000", "1"],
	        ["1397606400000", "1"],
	        ["1400457600000", "1"],
	        ["1400544000000", "1"],
	        ["1401148800000", "2"],
	        ["1406246400000", "5"],
	        ["1406246400000", "2"],
	        ["1406505600000", "2"],
	        ["1406505600000", "1"],
	        ["1406592000000", "1"],
	        ["1406678400000", "1"],
	        ["1407456000000", "1"],
	        ["1407456000000", "1"],
	        ["1408406400000", "1"],
	        ["1409097600000", "1"],
	        ["1409097600000", "1"],
	        ["1409184000000", "1"]
	      ],
	      "GREEN": [
	        ["1397433600000", "2"],
	        ["1397433600000", "1"],
	        ["1400025600000", "1"],
	        ["1400457600000", "1"],
	        ["1401148800000", "1"],
	        ["1407456000000", "1"],
	        ["1407715200000", "3"],
	        ["1409270400000", "1"]
	      ],
	      "TOTAL": [
	        [0, 0]
	      ]
	    }
	  };
	  var responseCount = responseCountData['alertCount'];
	  datasets = {
	    "Green": {
	      data: prepareData(responseCount.GREEN),
	      label: "Green flag",
	      color: "#00CC33"
	    },
	    "Yellow": {
	      data: prepareData(responseCount.YELLOW),
	      label: "Yellow flag",
	      color: "#FFFF00"
	    },
	    "Red": {
	      data: prepareData(responseCount.RED),
	      label: "Red flag",
	      color: "#FF0000"
	    },
	    "Total": {
	      data: responseCount.TOTAL,
	      label: "Total number of flags",
	      color: "#0000FF"
	    }
	  };
	  plotAccordingToChoices();
	}

	function prepareData(data) {
	  if (data && data.length > 0) {
	    var oneDay = 86400000;
	    var newData = [];

	    // new zero value point before the old first point
	    newData.push([(parseInt(data[0][0], 10) - oneDay).toString(), "0"]);

	    for (var i = 0; i < data.length; i++) {
	      // add existing point to new data
	      newData.push(data[i]);

	      // check distance between this point and the next (if not last point)
	      if (i < data.length - 1) {
	        var thisPointTimestamp = parseInt(data[i][0], 10);
	        var nextPointTimestamp = parseInt(data[i + 1][0], 10);

	        // if distance is two days, insert ony zero value point in between
	        if (nextPointTimestamp - thisPointTimestamp == 2 * oneDay) {
	          newData.push([(thisPointTimestamp + oneDay).toString(), "0"]);
	        }
	        // if distance is more then two days, insert one zero value point
	        // directly after this day and one directly before the next day
	        else if (nextPointTimestamp - thisPointTimestamp > 2 * oneDay) {
	          newData.push([(thisPointTimestamp + oneDay).toString(), "0"]);
	          newData.push([(nextPointTimestamp - oneDay).toString(), "0"]);
	        }
	      }
	    }

	    // new zero value point after the old last point
	    newData.push([(parseInt(data[data.length - 1][0], 10) + oneDay).toString(), "0"]);

	    return newData;
	  }
	}


	function plotAccordingToChoices() {

	  var data = [];
	  data.push(datasets["Green"]);
	  data.push(datasets["Yellow"]);
	  data.push(datasets["Red"]);
	  $.plot("#placeholder", data, {
	    xaxis: {
	      show: true,
	      mode: "time",
	      timeformat: "%m/%d"
	    },
	    yaxis: {
	      show: true,
	      tickDecimals: 0
	    },

	    grid: {
	      hoverable: true //IMPORTANT! this is needed for tooltip to work
	    },
	    tooltip: true,
	    tooltipOpts: {
	      content: function(label, x, y) {
	        var date = new Date(+x);
	        console.log(x, date);
	        var tooltip = '<h4>' + label + '</h4><ul>';
	        tooltip += '<li>Date is ' + date.toLocaleDateString() + '</li>';
	        tooltip += '<li>Total Count: ' + y + '</li></ul>';
	        return tooltip;
	      },
	      defaultTheme: false
	    },
	    points: {
	      show: true
	    },
	    series: {
	      lines: {
	        show: true,
	        label: {
	          show: false
	        }
	      },
	      points: {
	        show: true,
	        label: {
	          show: false
	        }
	      }
	    },

	    legend: {
	      show: false
	    }
	  });
	  var container = $("#placeholder");
	  // Create the X and Y axis labels
	  var xaxisLabel = $("<div id='xaxisLabel' class='axisLabel xaxisLabel'></div>")
	    .text("Date")
	    .appendTo(container);

	  var yaxisLabel = $("<div id='yaxisLabel' class='axisLabel yaxisLabel'></div>")
	    .text("Total Count")
	    .appendTo(container);
	}

	$(function() {
	  displayGraph();
	});
.demo-container {
  box-sizing: border-box;
  width: 850px;
  height: 450px;
  padding: 20px 15px 15px 15px;
  margin: 15px auto 30px auto;
  background: #fff;
}
.demo-placeholder {
  width: 100%;
  height: 100%;
  font-size: 14px;
  line-height: 1.2em;
}
.legend table {
  border-spacing: 5px;
}
.axisLabel {
  text-align: center;
  font-size: 12px;
}
.yaxisLabel {
  top: 50%;
  left: -30px;
  transform: rotate(-90deg);
  -o-transform: rotate(-90deg);
  -ms-transform: rotate(-90deg);
  -moz-transform: rotate(-90deg);
  -webkit-transform: rotate(-90deg);
  transform-origin: 0 0;
  -o-transform-origin: 0 0;
  -ms-transform-origin: 0 0;
  -moz-transform-origin: 0 0;
  -webkit-transform-origin: 0 0;
}
.ie7 .yaxisLabel,
.ie8 .yaxisLabel {
  top: 40%;
  font-size: 36px;
  filter: progid: DXImageTransform.Microsoft.Matrix(M11=0.0, M12=0.33, M21=-0.33, M22=0.0, sizingMethod='auto expand');
}
.xaxisLabel {
  top: 105%;
  left: 47%;
}
#content {
  width: 880px;
  margin: 0 auto;
  padding: 10px;
}
#chartModal {
  display: block;
}
#xaxisLabel {
  margin-top: 65%;
}
#yaxisLabel {
  margin-top: 10%;
  margin-left: -5%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="http://www.flotcharts.org/flot/jquery.flot.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.flot.tooltip/0.7.1/jquery.flot.tooltip.min.js"></script>
<script src="http://www.flotcharts.org/flot/jquery.flot.time.js"></script>
<script src="http://www.benjaminbuffet.com/public/js/jquery.flot.orderBars.js"></script>

<div class="modal fade action-modal ajax-modal enabled-modal modal-handler" id="chartModal">
  <div class="modal-dialog modal-lg" style="width:1000px">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
      </div>
      <div class="modal-body">
        <div id="content">
          <div class="demo-container">
            <div id="placeholder" class="demo-placeholder" style="float:left; width:675px;height:415px"></div>
            <div style="float:right;position:absolute; padding-left: 680px"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>