Sachin Verma
Sachin Verma

Reputation: 3812

Trendlines in google charts

I am using google charts library but could not draw a trendline may be because i am using a string as hAxis and number as vAxis, what i found till now is that it's impossible to draw a trendline until both axis are number, but i have seen example where Date as hAxis is used but i assume that's because that is comparable.
So can i draw a trendLine with xAxis as String?


My Code:

<script type="text/javascript">
    google.load('visualization', '1.1', {'packages': ['corechart'], 'callback': drawChart});

    function drawChart() {
     var data = new google.visualization.DataTable();
      <g:each status="counter" var="row" in="${transactionsColumns}">
        data.addColumn("${row[0]}","${row[1]}");
        </g:each>
        var tempData=new Array();
        <g:each status="counter" var="row" in="${transactionsData}">
        var lowerArray=new Array();
        <g:each status="eIndex" var="element" in="${row}">

        <g:if test="${eIndex==0}">
        var column="${row[eIndex]}"
        lowerArray[${eIndex}]=column;
        </g:if>
        <g:else>
        var column=${row[eIndex]}
        lowerArray[${eIndex}]=column;
        </g:else>

        </g:each>
        tempData[${counter}]=lowerArray;
        </g:each>
     data.addRows(tempData);


     var options = {'title':"${transactionsColumns[1][1]}",
             'width':'auto',
             'height':'auto',

             trendlines: {
               0: {
                 visibleInLegend: true,
                 color: 'purple',
                 lineWidth: 10,
                 opacity: 0.2,
               }
             }
             };

     var chart = new google.visualization.LineChart(document.getElementById("lineChart${divId}"));
     chart.draw(data, options);
    }
    </script>


EDIT: After jmac help i was able to do this:
Graph with string x-axis but actual a number

now i got what i wanted on hovering at graph points, but not on x-axis itself it still showing number
My code: this is one cell

lowerArray[${eIndex}]= {v:${counter+1},f:column};  //LHS dont care about it. v:loop_var(1,2,3..),f:"MyString"

Upvotes: 2

Views: 4203

Answers (2)

Ivan Ferrer
Ivan Ferrer

Reputation: 578

function drawMultipleTrendlineChart() {
    var chartType='columnChart';
    var collection = [];
    var chart = {
    "collection":[{
   "0": ["date", "Data"],
   "1": ["number", "Valor 1"],
   "2": ["number", "Valor 2"],
   "3": ["number", "Valor 3"],  
   "4": ["number", "Valor 4"],       
},
   {
   "0": ['2013-3-2', 200, 1000],
   "1": ['2013-4-2', 500, 650],
   "2": ['2013-5-2', 700, 550],
   "3": ['2013-6-2', 300, 95],
   "4": ['2013-8-2', 200, 75],
   "5": ['2013-9-2', 900, 1275],  
   "6": ['2013-10-2', 900, 1275],  
}]
};


    var data = new google.visualization.DataTable();
            var valores = [];
            for(var h=0; h <= chart.collection[0][0].length; h++){
                data.addColumn(chart.collection[0][h][0],
                chart.collection[0][h][1]);
            }
            var total = chart.collection[1][0].length;
            var params = [];

            for(var i=0; i<= total; i++){

                    var dataString = chart.collection[1][i][0];
                    var dataVenda = dataString.split('-');
                    var ano = eval(dataVenda[0]);
                    var mes = eval(dataVenda[1]);
                    var dia = eval(dataVenda[2]);
                    valores[i] = [new Date(ano, mes, dia),
                                  chart.collection[1][i][1],
                                  chart.collection[1][i][2]];

params[i] = '"'+i+'":{"showR2": false, "labelInLegend": \'valores\', "type": "exponencial", "visibleInLegend": true}';

            }
var parseData = eval('var dataParse = {'+params.join(',')+'}');
            data.addRows(valores);
          var formatter = new google.visualization.NumberFormat({
                fractionDigits: 2,
                prefix: 'R$:'
            });
            formatter.format(data, 1);
            var dateFormatter = new google.visualization.NumberFormat({
                pattern: 'MMM yyyy'
            });
            dateFormatter.format(data, 0);
            var chartHeight = 400;
            var chartWidth = 600;
            var chartOptions = {
                tooltip: {
                    isHtml: true
                },
                title: chart.title,
                isStacked: true,
                width: chartWidth,
                height: chartHeight,
                //colors: ['#0000D8', '#00dddd'],
                hAxis: {
                    title: 'Vendas por distribuidor',
                    slantedText: false,
                    slantedTextAngle: 45,
                    textStyle: {
                        fontSize: 10
                    },
                    format: 'dd-MM-yyyy'
                },
                chartArea: {
                    left: 50,
                    top: 20,
                    width: (chartWidth - 10),
                    height: (chartHeight - 90)
                }
            };
            chartOptions.trendlines = dataParse;
            chart = new google.visualization.LineChart(document.getElementById('multipleTrendChart'));
            chart.draw(data, chartOptions);
        }

google.load('visualization', '1', {
    packages: ['corechart'],
    callback: drawMultipleTrendlineChart
});

Upvotes: 1

jmac
jmac

Reputation: 7128

You can use a kludge to get around this.

Google supports having separate values for calculation and for display. You can give arbitrary numerical values to your data, and have it display as a string, allowing you to create a trendline.

For instance, if you have the following data set:

data.addColumn('string','Stations');
data.addColumn('number','Bentos Sold');
data.addRows([
  ['Tokyo',1],
  ['Shinagawa',2],
  ['Yokohama',3],
  ['Nagoya',4],
  ['Osaka',5]
]);

You can change this using {v: , f:} formatting as follows:

data.addColumn('number','Stations');
data.addColumn('number','Bentos Sold');
data.addRows([
  [{v:1, 'Tokyo'},1],
  [{v:2, 'Shinagawa'},2],
  [{v:3, 'Yokohama'},3],
  [{v:4, 'Nagoya'},4],
  [{v:5, 'Osaka'},5]
]);

Your axis values would still be 'Tokyo', 'Shinagawa', etc. but they would be calculated as numbers 1, 2, etc.

Upvotes: 3

Related Questions