Google Charts API折线图 - 如何在悬停时显示多个值?

时间:2012-11-28 18:01:13

标签: javascript charts google-visualization linechart

使用谷歌的折线图时,如果将鼠标悬停在一个点上,它会为您提供有关该点的信息。例如,如果某个点位于x:3, y:50且y轴称为英寸,则将鼠标悬停在这些点上会显示如下:

.----------.
|3         |
|Inches: 50|
`----------`

当我获取数据时,每个点也会存储一个额外的值。所以我的数组看起来像是[[3, 50, 20], [4, 52, 22], [5, 54, 24]],当我悬停时,我希望它看起来像这样:

.----------.
|Time: 3   |
|Inches: 50|
|Extra: 20 |
`----------`

所以我有两个问题是:

  1. 如何在x值之前添加'Time:'标签?
  2. 如何添加要显示的第3个值?
  3. 这是我的代码。这样做会创建第二行而不是将数据添加到一起。 You can look here看看我的意思。您也可以将鼠标悬停在积分上,看看我正在谈论的是悬停。我确信有一种简单的方法可以做到这一点,我只是遗漏了一些东西。

    function drawVisualization() {
        // Create and populate the data table.
        var data = google.visualization.arrayToDataTable([
          ['Time', 'Inches', 'Extra'],
          [  3   ,    50   ,    20  ],
          [  4   ,    52   ,    22  ],
          [  5   ,    54   ,    24  ]
        ]);
    
        // Create and draw the visualization.
        new google.visualization.LineChart(document.getElementById('visualization')).
            draw(data, {curveType: "function",
                        width: 500, height: 400,
                        vAxis: {title: 'Inches', maxValue: 10},
                        hAxis: {title: 'Time'}}
            );
    }
    
    google.setOnLoadCallback(drawVisualization);
    

2 个答案:

答案 0 :(得分:1)

我找到了解决方案。这不是我最喜欢的,因为重复数据不是最有效的方式,但无论如何,它是一个解决方案,所以我会在这里发布。

第一个问题来自我创建数据表的方式。 arrayToDataTable很有用,但它有限制。所以我离开了。这允许我添加自己的列,并在创建这些列时更具描述性。例如,关键是要分配role。所以我创建了前两列用于绘制图表的列,然后我添加了第三列,其类型为string,角色为tooltip

当我现在将数据添加到我的图表时,对于第三列,当我将鼠标悬停在一个点上时,我会准确传递我想要显示的内容。这就是重复数据的来源。这不是什么大问题,但我认为可能有更好/更直接的方式。无论如何,here is a link to my new chart,这是我的代码:

function drawVisualization() {
    // Create and populate the data table.
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Time');
    data.addColumn('number', 'Inches');
    data.addColumn({type: 'string', role: 'tooltip'});

    data.addRow(['3', 50, 'Time: 3\n Inches: 50\n Extra: 20']);
    data.addRow(['4', 52, 'Time: 4\n Inches: 52\n Extra: 22']);
    data.addRow(['5', 54, 'Time: 5\n Inches: 54\n Extra: 24']);

    // Create and draw the visualization.
    new google.visualization.LineChart(document.getElementById('visualization')).
        draw(data, {curveType: "function",
                    width: 500, height: 400,
                    vAxis: {title: 'Inches', maxValue: 10},
                    hAxis: {title: 'Time'}}
        );
}

google.setOnLoadCallback(drawVisualization);

答案 1 :(得分:1)

我解决了这个问题,将“focusTarget:'category'”添加到选项中:

draw(data,{..., focusTarget: 'category'}