【问题标题】:How Draw Vertical Line to Histogram Graph on Google Charts?如何在谷歌图表上为直方图绘制垂直线?
【发布时间】:2014-02-24 07:42:17
【问题描述】:

如果我绘制折线图没有问题,但我想在直方图上显示它.. (https://developers.google.com/chart/interactive/docs/gallery/histogram)

对于折线图;

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

直方图;

var chart = new google.visualization.Histogram(document.querySelector('#chart_div'));

其他代码;

function drawChart () {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Name');
    data.addColumn({type: 'string', role: 'annotation'});
    data.addColumn('number', 'Value');

    data.addRows([
        ['Foo', null, 4],
        ['Bar', null, 3],
        ['Baz', null, 7],
        ['Bat', null, 9],
        ['Cad', 'Vertical line here', 9],
        ['Qud', null, 2],
        ['Piz', null, 6]
    ]);

    var chart = new google.visualization.Histogram(document.querySelector('#chart_div'));
    chart.draw(data, {
        height: 300,
        width: 400,
        annotation: {
            // index here is the index of the DataTable column providing the annotation
            1: {
                style: 'line'
            }
        }
    });
}

【问题讨论】:

    标签: javascript google-visualization histogram


    【解决方案1】:

    Daniel LaLiberte 在 Google Groups 上回答了我的问题,他是 Google 的高级软件工程师。

    https://groups.google.com/forum/#!msg/google-visualization-api/7y3LrKETEwY/fR4HoYwBu-EJ

    所以在谷歌图表上是不可能的..

    但是 :) Google Charts 使用 SVG.. 用于 exp。我想在 30 x 轴上画一条线..

    var newLine = document.createElementNS('http://www.w3.org/2000/svg', 'line');
    newLine.setAttribute('id', 'lineId');
    newLine.setAttribute('style', 'stroke:rgb(0,0,0); stroke-width:3;');        
    newLine.setAttribute('x1', chart.getChartLayoutInterface().getXLocation(30));
    newLine.setAttribute('y1', chart.getChartLayoutInterface().getChartAreaBoundingBox().top);
    newLine.setAttribute('x2', chart.getChartLayoutInterface().getXLocation(30));
    newLine.setAttribute('y2', chart.getChartLayoutInterface().getChartAreaBoundingBox().height + chart.getChartLayoutInterface().getChartAreaBoundingBox().top);
    $("svg").append(newLine);
    

    【讨论】:

    • 对于未来的访问者:这也可以用来为折线图上的“注释”线设置动画 - 我找不到任何方法让谷歌图表为注释的变化位置设置动画,但是在上面的代码中绘制线条的 X 位置动画非常简单。感谢您朝着正确的方向推动,dustqm!
    • 这太完美了。感谢您提供示例代码,您是真正的英雄!