Google charts trendline not showing

你离开我真会死。 提交于 2020-01-03 08:37:29

问题


I have a Google chart line chart that I want to show a trendline on, but it doesn't show up.

The data is fetched from a database and the javascript is generated by PHP but the resulting javascript looks like this:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">

// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});

// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);

// Callback that creates and populates a data table, 
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
    var dataS = new google.visualization.DataTable();
    dataS.addColumn('string', 'Dag');
    dataS.addColumn('number', 'Poäng');
    dataS.addRows([
        ['1', 32],
        ['2', 37],
        ['3', 37],
        ['4', 40],
        ['5', 31],
        ['6', 38],
        ['7', 28],
        ['8', 34],
        ['9', 41],
        ['10', 41],
    ]);

    var optionsS = {
      title: '',
      legend: 'none',
      hAxis: {title: 'Serie'},
      vAxis: {title: 'Poäng'},
      pointSize: 4,
      trendlines: { 0: {} }
    };

    // Instantiate and draw our chart, passing in some options.
    var chart = new google.visualization.LineChart(document.getElementById('chart_div_series'));
    chart.draw(dataS, optionsS);
}
</script>

The script is mainly copypaste from the Google charts example. The chart works fine, except for the trend line not showing up. Any ideas why?


回答1:


You have to have a continuous domain axis (type "number", "date", "datetime", or "timeofday") in order to use a trendline. By setting your first column to a "string" type (and populating it with strings), you are disabling the trendline. Switch to a "number" type column, and the trendline will work:

var dataS = new google.visualization.DataTable();
dataS.addColumn('number', 'Dag');
dataS.addColumn('number', 'Poäng');
dataS.addRows([
    [1, 32],
    [2, 37],
    [3, 37],
    [4, 40],
    [5, 31],
    [6, 38],
    [7, 28],
    [8, 34],
    [9, 41],
    [10, 41]
]);


来源:https://stackoverflow.com/questions/19642276/google-charts-trendline-not-showing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!