如何在Google图表上绘制直线柱状图?

4
如果我绘制折线图没有问题,但我想在直方图上显示它.. (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'
            }
        }
    });
}
1个回答

5

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

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

所以在 Google Charts 上是不可能实现的。

但是 :) Google Charts 使用 SVG.. 例如,我想要画一条线到 x 轴 30。

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);

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接