5

https://developers.google.com/chart/interactive/docs/gallery/linechart

Hello, guys, I would like to know that is there a way to change the color of the line when it is moving down. I have googled but I was not able to find anything.

like e.g the line graph is moving upwards it's ok as soon as the graph line tilts downward than that downward should only be red. If after that it moves upward then the upward line should not be red.

Here is a screenshot of what I'm trying to obtain: https://i.stack.imgur.com/8ZLc0.jpg

If anybody knows this please help me

Here is my code of what am I doing right now:

function draw_chart(chart_data, id, action)
{
    var url = base_url + "controller/function/" + id ;
    statData = getAjax(url, '', false, 'json');
    minimum = '';
    maximum = '';
    upside = '';

    if (statData.min) {
        minimum = statData.min;
    }
    if (statData.max) {
        maximum = statData.max;
    }
    if (statData.upside == '1') {
        upside = -1;
    }

    value = $("#value_" + id).val();
    var name = $('#name_' + id).val();
    var names = [];
    if (value == 2) {
        var names = name.split('/');
    } else {
        names[0] = name;
    }
    title = $("#name_" + id).val();
    google.load('visualization', '1.1', {packages: ['line', 'corechart']});
    format = $("#format-select_" + id + " option:selected").val();

    if (statData.row[0].type == 'currency') {
        format = '$#';
    } 
    var options = {
        title: title,
        width: 820,
        height: 500,
        titlePosition: 'none',
        legend: 'none',
        lineWidth: 3,
        annotation: {
            0: { style: "line"},
            1: { style: "line"}
        },
        series: {0: { style: "area"} , 1: {type: "area"}},    
        animation: {duration: 1000, easing: 'in'},
        strictFirstColumnType: true,
        fontColor: "#333333",
        fontSize: "12px",
        colors: ["#5AA023", "#3F5F9F" , ""],
        pointSize: 6,
        fontSize: 11,
        enableEvents: true,
        forceIFrame: false,
        tooltip: {showColorCode: false, },
        vAxis: {
                gridlines:{color: "#E6E6E6"},
                textStyle:{color: "#666666"}, 
                baselineColor: "#CACACA", 
                format: format,
                viewWindow:{
                    min: minimum,
                    max: maximum
                },
                direction: upside,                
            },
        hAxis: {gridlines:{color: "#E6E6E6" , count:chart_data.length}, 
                baselineColor: "#CACACA",  
                textStyle:{color: "#666666"}, 
                format: "MMM dd yyyy",
                textPosition: "out", 
                slantedText: true,
                },
        chartArea: {height: 420, width: 750, top: 14, left: 45, right: 0}
    };
    if (action && action == "update") {
        //alert(action);
    }
    else {

            var chart_div = document.getElementById('chart'+id);
            var chart_div1 = document.getElementById('chart1'+id);

            var  chart = new google.visualization.LineChart(chart_div);
            google.visualization.events.addListener(chart, 'select', clickHandler);

            data = new google.visualization.DataTable();
            data.addColumn('string', 'Season Start Date');
            data.addColumn({type: 'string', role: 'annotation'});
            data.addColumn('number', names[0].trim());

            if (value == 2) {
                data.addColumn('number', names[1].trim());
                for (i = 0; i < chart_data.length; i++)
                    data.insertRows(0, [[new Date(chart_data[i].date), parseInt(chart_data[i].val), parseInt(chart_data[i].val1)]]);
        }
        else {
                for (i = 0; i < chart_data.length; i++) {
                    if (!chart_data[i].quarter) {
                        date = chart_data[i].date.split('-');
                        month = getMonthName(date[1]);
                        day = date[2];
                        year = date[0];
                        data.insertRows(0, [[month+' '+day+' '+year , '.' , parseInt(chart_data[i].val) ]]);
                    } else {
                        data.insertRows(0, [[chart_data[i].quarter , '.' , parseInt(chart_data[i].val) ]]);
                    }
                }    
        }
    }
}
if (statData.row[0].type == 'currency') {
    var formatter = new google.visualization.NumberFormat({prefix: '$'});
    formatter.format(data, 1);
} 
    var dataView = new google.visualization.DataView(data);
  dataView.setColumns([
    // reference existing columns by index
    0, 1,
    // add function for line color
    {
      calc: function(data, row) {
        console.log("ok world!");
        var colorDown = '#0000FF';
        var colorUp = 'green';

        if ((row === 0) && (data.getValue(row, 1) < data.getValue(row + 1, 1))) {
          return colorDown;
        } else if ((row > 0) && (data.getValue(row - 1, 1) < data.getValue(row, 1))) {
          return colorDown;
        }
        return colorUp;
      },
      type: 'string',
      role: 'style'
    }
  ]);
    chart.draw(dataView, options);
Gardezi
  • 2,692
  • 2
  • 32
  • 62

1 Answers1

11

use a DataView and setColumns to provide a function that determines line direction
and returns the appropriate line color

see following working snippet...

google.charts.load('current', {
  callback: drawLineColors,
  packages: ['corechart']
});

function drawLineColors() {
  var data = new google.visualization.DataTable();
  data.addColumn('number', 'X');
  data.addColumn('number', 'Y');
  data.addRows([
    [0, 2000],
    [3, 1700],
    [6, 1400],
    [9, 2500],
    [12, 3000],
    [15, 4700],
    [18, 2200],
    [21, 1500],
    [24, 1200],
    [27, 1800],
    [30, 2600],
    [33, 2800],
    [36, 3000],
    [39, 2300],
    [42, 2000],
    [45, 4000]
  ]);

  var options = {
    curveType: 'function',
    height: 200,
    legend: {
      position: 'top'
    }
  };

  var dataView = new google.visualization.DataView(data);
  dataView.setColumns([
    // reference existing columns by index
    0, 1,
    // add function for line color
    {
      calc: function(data, row) {
        var colorDown = '#0000FF';
        var colorUp = '#FF0000';

        if ((row === 0) && (data.getValue(row, 1) < data.getValue(row + 1, 1))) {
          return colorDown;
        } else if ((row > 0) && (data.getValue(row - 1, 1) < data.getValue(row, 1))) {
          return colorDown;
        }
        return colorUp;
      },
      type: 'string',
      role: 'style'
    }
  ]);

  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
  chart.draw(dataView, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
WhiteHat
  • 59,912
  • 7
  • 51
  • 133
  • Hello, whiteHat thanks for the help. Since I'm not using dataView can you please tell how will I achieve it in my code. I have pasted my code to – Gardezi Oct 20 '16 at 12:33
  • recommend using a DataView -- otherwise, just need to add a `'style'` column and set the row value to the color the line for that row should be... – WhiteHat Oct 20 '16 at 12:52
  • The code that I pointed out I'm using it at a lot of places. If I changed it I would have to change it at a lot of places that's why I'm asking if there is any way I could do it in my existing code – Gardezi Oct 20 '16 at 12:56
  • It would be a great help if you could show me how can I do it with my existing code. Thanks – Gardezi Oct 20 '16 at 12:58
  • you would only need to change it in one place, just before `draw`, which i don't see in the code above -- would need a sample of the data in order to build a working example – WhiteHat Oct 20 '16 at 12:59
  • oh sorry draw was left out when I was copying. but isn't this all available with dataView. I'm using dataTable not dataView – Gardezi Oct 20 '16 at 13:03
  • dataview is built from an existing datatable -- see code in my answer -- after your table is built and before chart is drawn, create view and use it in draw -- simple really – WhiteHat Oct 20 '16 at 13:12
  • ok let me try. If I have any problem I'll get back to you if that's not a problem – Gardezi Oct 20 '16 at 13:13
  • Hi @WhiteHat Is it possible with vue-google-charts? – Hemant Sah Feb 24 '23 at 16:26
  • @HermantSah -- I don't see why it wouldn't be possible with vue-google-charts – WhiteHat Feb 25 '23 at 18:22