在Google折线图中绘制基线

时间:2014-07-25 14:37:02

标签: javascript google-visualization

我使用谷歌折线图我想画一条基线,但我不知道该怎么办呢,例如我想在2004年400到600之间画线,我该怎么办呢 谷歌示例:

<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales', 'Expenses'],
          ['2004',  1000,      400],
          ['2005',  1170,      460],
          ['2006',  660,       1120],
          ['2007',  1030,      540]
        ]);

        var options = {
          title: 'Company Performance'
        };

        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

您可以通过几种不同的方式执行此操作,具体取决于您要实现的目标。最简单的方法是使用&#34; interval&#34;角色列:

function drawChart() {
    var data = google.visualization.arrayToDataTable([
        ['Year', 'Sales', 'Expenses', {role: 'interval', type: 'number'}, {role: 'interval', type: 'number'}],
        ['2004', 1000, 400, 400, 600],
        ['2005', 1170, 460, null, null],
        ['2006', 660, 1120, null, null],
        ['2007', 1030, 540, null, null]
    ]);

    var options = {
        title: 'Company Performance'
    };

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

您可以使用间隔进行相当多的自定义,请参阅documentation

另一种方法是为此行添加一系列新数据,从&#34; string&#34;更改第一列的数据类型。 to&#34; number&#34;,并添加具有相同x值的多行数据,例如:

function drawChart() {
    var data = google.visualization.arrayToDataTable([
        ['Year', 'Sales', 'Expenses', 'vertical lines'],
        [2004, 1000, 400, 400],
        [2004, null, null, 600],
        [2005, 1170, 460, null],
        [2006, 660, 1120, null],
        [2007, 1030, 540, null]
    ]);

    var options = {
        title: 'Company Performance',
        interpolateNulls: true, // this prevents your other lines from breaking
        series: {
            2: {
                // these options control your new series for the vertical lines
                visibleInLegend: false, // hide from the legend
                enableInteractivity: false // make the line non-interactive
                color: '#9055a6' // set the color of the line
                // etc...
            }
        }
    };

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