Google 折线图将悬停标题添加到 X 值

Google Line Chart Add Hover Title To X Value

当我将鼠标悬停在我的线上的一个点上时 chart/graph 我只得到 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' 其中仍然 returns 只有 Y 标题。我还附上了截图。

基本上您需要添加 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);
}

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

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

https://jsfiddle.net/6tf2fatz/