سؤال

Is there a way to make certain candlesticks a different color when using the Google Charts API?

For example, take a look at the following (editable) candlestick chart:

https://code.google.com/apis/ajax/playground/?type=visualization#candlestick_chart

    function drawVisualization() {
   // Populate the data table.
    var dataTable = google.visualization.arrayToDataTable([
       ['Mon', 20, 28, 38, 45],
       ['Tue', 31, 38, 55, 66],
       ['Wed', 50, 55, 77, 80],
       ['Thu', 77, 77, 66, 50],
       ['Fri', 68, 66, 22, 15]
    // Treat first row as data as well.
    ], true);

    // Draw the chart.
    var chart = new google.visualization.CandlestickChart(document.getElementById('visualization'));
    chart.draw(dataTable, {legend:'none', width:600, height:400});
}

​Is there a way to make, say, just the 'Tue' candlestick red while keeping the rest blue/white?

هل كانت مفيدة؟

المحلول

It seems there is no chart option to set that.

One possibility is to build two series from your data and set different color for each series. Input data has to be changed. Tue data are moved to the second series, all other values are zero:

    var data = google.visualization.arrayToDataTable([
      ['Mon', 20, 28, 38, 45,  0, 0, 0, 0],
      ['Tue',  0,  0,  0,  0, 31, 38, 55, 66,],
      ['Wed', 50, 55, 77, 80,  0, 0, 0, 0],
      ['Thu', 77, 77, 66, 50,  0, 0, 0, 0],
      ['Fri', 68, 66, 22, 15,  0, 0, 0, 0]
      // Treat first row as data as well.
    ], true);

    var options = {
        legend: 'none',
        bar: {
            groupWidth: 100
        },
        series: {
            0: {color: '#4682B4'},
            1: {color: '#FF8C00'}
        }
    };

See example at jsbin. Not beautiful one because there is an offset for the second series.

The other possibility is to change SVG element property values. Each candlestick is build using something like:

<g>
<rect x="235" y="279" width="2" height="115" stroke="none" stroke-width="0" fill="#4682b4"></rect>
<rect x="213" y="312" width="47" height="44" stroke="#4682b4" stroke-width="2" fill="#4682b4"></rect>
</g>

So you have to filter out <rect> elements and change fill property for one which you want to have different color.

Update: That could be done, for example using methods querySelectorAll() and setAttribute():

    var cSticks = document.querySelectorAll('rect[fill="#4682b4"]');

    cSticks[2].setAttribute('fill', '#ff8c00');
    cSticks[3].setAttribute('fill', '#ff8c00');
    cSticks[3].setAttribute('stroke', '#ff8c00');

See updated example at jsbin with hardcoded data.

Note: fill color values are lowercase so if you search for 4682B4, nothing is found.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top