Google Line Chart将悬停标题添加到X值

时间:2015-08-31 08:55:53

标签: javascript google-visualization

当我将鼠标悬停在折线图/图表中的某个点上时,我只得到Y值,而不是X值。

我得到了什么:

36
速度:120

我想要的是什么:

距离:36

速度:120

代码:

<script type="text/javascript" src="https://www.google.com/jsapi" ></script>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);

function drawChart() {

      var data = new google.visualization.DataTable();
      data.addColumn('number', "Distance");
      data.addColumn('number', "Speed");

      data.addRows(<?php echo json_encode($DistanceSpeedArray,  JSON_NUMERIC_CHECK); ?>);

        var options = {
         focusTarget: 'category',

      backgroundColor: 'none',
      chartArea: {
            backgroundColor: 'transparent',
            left: 40,
            top: 40,
            width: 1200,
            height: 350
        },


      legend: {
          position: 'top'
      },
      hAxis: {title: 'Distance (KM)',  titleTextStyle: {color: 'black'}},
      //vAxis: {title: 'Speed (KM/H)',  titleTextStyle: {color: 'black'}},
    colors: ['green'],


      crosshair: {
          orientation: 'vertical'
      },
      animation: {
          startup: true,
          duration: 5000
      },
      }; 

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

      chart.draw(data, options);
}

上面的代码是一个完整的代码,包括focusTarget:'category',它仍然只返回Y标题。我还附上了截图。enter image description here

2 个答案:

答案 0 :(得分:1)

您可以将格式应用于距离列

new google.visualization.PatternFormat("Distance: {0}")
    .format(data, [0], 0);

https://jsfiddle.net/6tf2fatz/

答案 1 :(得分:0)

基本上,您需要添加focusTarget: 'category'以专注于沿主轴的所有数据点的分组。 试试以下代码,

<script type="text/javascript" src="https://www.google.com/jsapi" ></script>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);

function drawChart() {

    var data = new google.visualization.DataTable();
    data.addColumn('number', 'Distance');
    data.addColumn('number', "Speed");

    data.addRows(<?php echo json_encode($DistanceSpeedArray,  JSON_NUMERIC_CHECK); ?>);

    ...

    var options = { focusTarget: 'category' };

    var chart = new google.visualization.LineChart(document.getElementById('your_div_chart'));
    chart.draw(data, options);
}