【问题标题】:Google Chart API - different color for certain candlesticksGoogle Chart API - 某些烛台的不同颜色
【发布时间】:2014-06-03 02:01:25
【问题描述】:

在使用 Google Charts API 时,有没有办法让某些烛台变成不同的颜色?

例如,看看下面的(可编辑的)烛台图:

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});
}

​有没有办法让“周二”烛台变成红色,而其余的保持蓝色/白色?

【问题讨论】:

    标签: javascript google-visualization


    【解决方案1】:

    似乎没有图表选项可以设置。

    一种可能性是根据您的数据构建两个系列并为每个系列设置不同的颜色。必须更改输入数据。 Tue 数据被移到第二个系列,所有其他值都为零:

        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'}
            }
        };
    

    example at jsbin。不是很漂亮,因为第二个系列有一个偏移量。

    另一种可能性是更改 SVG 元素的属性值。每个烛台都是使用以下内容构建的:

    <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>
    

    因此,您必须过滤掉 &lt;rect&gt; 元素并更改 fill 属性以获得您想要具有不同颜色的元素。

    更新:这可以做到,例如使用方法querySelectorAll()setAttribute()

        var cSticks = document.querySelectorAll('rect[fill="#4682b4"]');
    
        cSticks[2].setAttribute('fill', '#ff8c00');
        cSticks[3].setAttribute('fill', '#ff8c00');
        cSticks[3].setAttribute('stroke', '#ff8c00');
    

    使用硬编码数据查看更新的example at jsbin

    注意:填充颜色值是小写的,所以如果你搜索 4682B4,什么都找不到。

    【讨论】:

    • 谢谢@anto,我会接受这个,因为它是正确的答案并且非常有帮助。我最终使用了一个组合图表,其中不相关的蜡烛被替换为折线图系列(烛台值为 null),并将相关的烛台留在原处(线值为 null)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    相关资源
    最近更新 更多