折线图切片可计算两点之间的差异(实际和百分比)

时间:2019-06-03 07:25:22

标签: javascript charts google-visualization

我有一个使用Google注释图表从CSV文件成功构建的注释折线图表。 (感谢Whitehat的帮助。)

我在Google图表示例中未成功查找,无法找到一种方法来获取折线图的一部分,然后在两点之间进行一些计算,例如差异和百分比差异。我可能还需要做进一步的计算,但是目前这两个已经足够了。

基本上,我正在尝试构建Google股价图之类的功能

enter image description here

到目前为止的代码:

<html>

  <head>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

                <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>

                <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

    <script type='text/javascript'>





// load google charts

google.charts.load('current', {

  packages: ['annotationchart']

}).then(function () {

  // declare data variable

  var arrayData;



  // get csv data

  $.get('test.csv', function(csvString) {

    // get csv data success, convert to an array, draw chart

    arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});

    drawChart(arrayData);

  })

});



// draw chart

function drawChart(arrayData) {

  // convert string in first column to a date

  arrayData = arrayData.map(function (row) {

    return [new Date(row[0]),row[1],row[2]];

  });



  // create google data table, chart, and options

  var data = google.visualization.arrayToDataTable(arrayData);

  var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));

  var options = {

    displayAnnotations: true

  };



  // draw chart

  chart.draw(data, options);

}             



    </script>

  </head>



  <body>

    <div id='chart_div' style='width: 1200x; height: 700px;'></div>

  </body>

</html>

有什么想法我可以去做吗?

1 个答案:

答案 0 :(得分:1)

您可以使用鼠标事件来允许用户在图表上进行选择。

给出选择的坐标,
使用chart methods getChartLayoutInterfacegetHAxisValue
确定用户选择的值的范围。

请参阅以下工作片段,
点击图表并按住鼠标,然后拖动以绘制选择。
放开鼠标时,将显示所选的值。

google.charts.load('current', {
  packages: ['controls', 'corechart']
}).then(function () {
  // build data table
  var oneDay = (24 * 60 * 60 * 1000);
  var dateEnd = new Date();
  var dateStart = new Date(dateEnd.getTime() - (oneDay * 365.25));
  var data = new google.visualization.DataTable();
  data.addColumn('date', 'Date');
  data.addColumn('number', 'Y');
  for (var i = dateStart.getTime(); i <= dateEnd.getTime(); i = i + oneDay) {
    var direction = (i % 2 === 0) ? 1 : -1;
    var rowDate = new Date(i);
    data.addRow([rowDate, rowDate.getFullYear() + (rowDate.getDate() * direction)]);
  }

  // chart options
  var options = {
    chartArea: {
      height: '100%',
      width: '100%',
      top: 24,
      left: 60,
      right: 16,
      bottom: 60
    },
    hAxis: {
      format: 'MMM-yyyy'
    },
    height: '100%',
    legend: {
      position: 'top'
    },
    width: '100%'
  };

  // create chart and elements
  var container = document.getElementById('chart');
  var values = document.getElementById('values');
  var chart = new google.visualization.LineChart(container);

  // wait until chart is ready
  google.visualization.events.addListener(chart, 'ready', function () {
    // initialize variables
    var chartLayout = chart.getChartLayoutInterface();
    var chartArea = chartLayout.getChartAreaBoundingBox();
    var chartBounds = container.getBoundingClientRect();
    var select = document.getElementById('select');
    var x1 = 0;
    var y1 = 0;
    var x2 = 0;
    var y2 = 0;
    var x3 = 0;
    var y3 = 0;
    var x4 = 0;
    var y4 = 0;

    // listen for mouse events
    window.addEventListener('mousedown', function (e) {
      select.className = '';
      x1 = e.pageX;
      y1 = e.pageY;
      reCalc();
    });
    window.addEventListener('mousemove', function (e) {
      if (select.className === '') {
        x2 = e.pageX;
        y2 = e.pageY;
        reCalc();
      }
    });
    window.addEventListener('mouseup', function (e) {
      select.className = 'static';
      selectPoints();
    });

    // show user selection
    function reCalc() {
      x3 = Math.min(x1,x2);
      x4 = Math.max(x1,x2);
      y3 = Math.min(y1,y2);
      y4 = Math.max(y1,y2);
      select.style.left = x3 + 'px';
      select.style.width = x4 - x3 + 'px';
      select.style.top = (chartBounds.top + chartArea.top + window.pageYOffset) + 'px';
      select.style.height = (chartArea.height + window.pageYOffset) + 'px';
    }

    // show values from selection
    function selectPoints() {
      if ((((chartBounds.left + window.pageXOffset) <= x3) &&
           ((chartBounds.left + chartBounds.width + window.pageXOffset) >= x4)) &&
          (((chartBounds.top + window.pageYOffset) <= y3) &&
           ((chartBounds.top + chartBounds.height + window.pageYOffset) >= y4))) {
        var rows = data.getFilteredRows([{
          column: 0,
          minValue: chartLayout.getHAxisValue(x3),
          maxValue: chartLayout.getHAxisValue(x4)
        }]);

        values.innerHTML = '';
        rows.forEach(function (index) {
          var value = values.appendChild(document.createElement('div'));
          value.innerHTML = data.getFormattedValue(index, 0) + ': ' + data.getFormattedValue(index, 1);
        });
      }
    }
  });

  // draw chart
  chart.draw(data, options);
});
#select {
  background-color: #3366cc;
  border: 1px solid #3366cc;
  opacity: 0.2;
  position: absolute;
  z-index: 1000;
}

.hidden {
  display: none;
  visibility: hidden;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div class="hidden" id="select"></div>
<div id="chart"></div>
<div id="values"></div>