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

标签 javascript charts flot

enter image description here我使用数据点生成了流程图。我没有对 x 轴和 y 轴使用刻度。原因是我的数据集变化很大。

现在流程图可以很好地生成图表了。但当没有数据时,它会在滴答声之间中断。 如果没有数据,如何设置默认 y 轴值?

最佳答案

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

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>

关于javascript - 当图表中特定 x 轴不存在数据时如何设置默认 y 轴值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26166197/

相关文章:

javascript - 如何使用 jquery mobile 创建选项卡?

c# - 如何将ms sql数据传递给jquery float

java - 寻找DICOM ECG查看器开源HTML5或任何基于Web的代码

javascript - Chartjs v2 描边阴影

javascript - 使用 angular.js 中的 OAuth2 创建的 token 管理身份验证

javascript - 从 Doc 函数中删除空对象

javascript - 如何防止我的 HighChart 条形图倒转?

javascript - 当用户使用 ShieldUI 单击 ChartLegend 时,如何禁用隐藏/显示图表的功能?

Excel 2003 图表 : Chart Data Too Complex

javascript - 重新定位平面图的图例