条形图无法更改单个条形颜色

条形图无法更改单个条形颜色

本文介绍了Google 条形图无法更改单个条形颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 Google Visualization API 创建了一个 google 条形图,我正在尝试添加一个用于样式的列.这是我在下面使用 .addcolumn() 的实现,然后将颜色字段添加到每一行,但是每个条形仍然是默认的蓝色.

//运行 onload 构建第一个默认图表并加载条形图包var jsonCoachCount;window.onload = 函数(){jsonCoachCount = JSON.parse('[{"Service_Count":"4","Name":"Other"}, {"Service_Count":"4","Name":"校园网络"},{"Service_Count":"3","Name":"Learn@UW"},{"Service_Count":"2","Name":"Customer Service"},{"Service_Count":"1","Name":"Blackboard Collaborate"},{"Service_Count":"1","Name":"Office 365"},{"Service_Count":"1","Name":"Multiple"},{"Service_Count":"1","Name":"Office-ionado"},{"Service_Count":"1","Name":"Case Notes"},{"Service_Count":"1","Name":"ResNet"}]');//加载可视化 API 和条形图包.google.charts.load('current', {'packages': ['bar']});//设置在加载 Google Visualization API 时运行的回调.google.charts.setOnLoadCallback(drawChart);};函数 drawChart(){var servicesData = new google.visualization.DataTable();servicesData.addColumn('string', 'Service');servicesData.addColumn('number', 'Number of Coach');servicesData.addColumn({type:'string', role:'style'});for(i = 0; i < jsonCoachCount.length; i++){tempArray =[];tempArray.push(String (jsonCoachCount[i]['Name']),parseInt(jsonCoachCount[i]['Service_Count']),'红色');servicesData.addRow(tempArray);}变量选项 = {背景颜色: {填充:'#E8E4D8'},图例:{位置:'无'},标题文本样式:{粗体:'真实'},图表: {title: '服务教练',副标题:按服务分类的教练:从 2016 年 9 月 10 日到今天"},酒吧: {组宽度:'60%'},'hAxis':{文字样式:{字体大小:11}}};var chart = new google.charts.Bar(document.getElementById('servicesChart'));chart.draw(servicesData, google.charts.Bar.convertOptions(options));}

我不确定我哪里出错了,或者我是否误解了文档的一部分.感谢您帮助我更改条形图上的条形颜色,谢谢!

解决方案

colors 选项中的每种颜色都应用于数据表中的每个系列/y 轴列.
如果只有一个 y 轴列,则只会应用一种颜色.

否则,样式列角色是最简单的方法为单个条着色.
但是,它不适用于材料图表.

有关选项,请参阅示例图表...

图表 1 = 材料图表
图表 2 = 核心图表
两者都使用不同的样式设置以相同的方式构建
适用于 Core,而不适用于 Material

如果您对每个条形的颜色都满意...

图表 3 = 材料图表
使用 colors 配置选项将颜色更改为红色
只有一个系列,所以只接受一种颜色

如果您必须为每个条形使用不同颜色的材料图表...

图表 4 = 材料图表
每个值都添加为一列而不是一行,从而创建多个系列
使用 colors 配置选项更改每个条的颜色
series 选项也可以在这里使用
但是,使用起来要困难得多,请注意 Spacer 列和缺少 hAxis 标签...

google.charts.load('current', {回调:初始化,包:['bar','corechart']});函数初始化(){var jsonCoachCount = JSON.parse('[{"Service_Count":"4","Name":"Other"}, {"Service_Count":"4","Name":"校园网络"},{"Service_Count":"3","Name":"Learn@UW"},{"Service_Count":"2","Name":"客户服务"},{"Service_Count":"1","Name":"Blackboard协作"},{"Service_Count":"1","Name":"Office 365"},{"Service_Count":"1","Name":"Multiple"},{"Service_Count":"1","Name":"Office-ionado"},{"Service_Count":"1","Name":"Case Notes"},{"Service_Count":"1","Name":"ResNet"}]');变量选项 = {背景颜色: {填充:'#E8E4D8'},图例:{位置:'无'},标题文本样式:{粗体:'真实'},图表: {title: '服务教练',副标题:按服务分类的教练:从 2016 年 9 月 10 日到今天"},酒吧: {组宽度:'60%'},h轴:{文字样式:{字体大小:11}}};绘制图表();drawSeriesChart();函数 drawChart() {var servicesData = new google.visualization.DataTable();servicesData.addColumn('string', 'Service');servicesData.addColumn('number', 'Number of Coach');servicesData.addColumn({type:'string', role:'style'});for (i = 0; i < jsonCoachCount.length; i++) {var tempArray =[];var tempColor;开关 (i) {案例0:tempColor = '颜色:红色';休息;情况1:tempColor = '橙色';休息;案例2:tempColor = '填充颜色:金色;';休息;案例3:tempColor = 'bar {color: green;}';休息;案例4:tempColor = 'bar {fill-color: blue;}';休息;默认:tempColor = 'bar {填充颜色:青色;笔触颜色:黑色;笔画宽度:4;}';}tempArray.push(字符串 (jsonCoachCount[i]['Name']),parseInt(jsonCoachCount[i]['Service_Count']),临时颜色);servicesData.addRow(tempArray);}var chart = new google.charts.Bar(document.getElementById('servicesChart1'));chart.draw(servicesData, google.charts.Bar.convertOptions(options));var chart = new google.visualization.ColumnChart(document.getElementById('servicesChart2'));图表绘制(服务数据,选项);//只有一个系列存在——只有一种颜色有效options.colors = ['红色'];var chart = new google.charts.Bar(document.getElementById('servicesChart3'));chart.draw(servicesData, google.charts.Bar.convertOptions(options));}函数 drawSeriesChart() {var servicesData = new google.visualization.DataTable();servicesData.addColumn('string', 'Service');for (i = 0; i < jsonCoachCount.length; i++) {servicesData.addColumn('number', String (jsonCoachCount[i]['Name']));servicesData.addColumn('number', 'Spacer');}var tempArray = [];tempArray.push('教练人数');for (i = 0; i < jsonCoachCount.length; i++) {tempArray.push(parseInt(jsonCoachCount[i]['Service_Count']));tempArray.push(null);}servicesData.addRow(tempArray);options.colors = ['深粉','红色的','橘子','金子','绿色','蓝色','靛青','紫色的','紫色','粉色的'];var chart = new google.charts.Bar(document.getElementById('servicesChart4'));chart.draw(servicesData, google.charts.Bar.convertOptions(options));}}
div {填充:2px 0px 2px 0px;字体粗细:粗体;}.代码 {背景颜色:浅灰色;字体系列:Courier New;}
<script src="https://www.gstatic.com/charts/loader.js"></script><div>1.材料图表

<div id="servicesChart1"></div><div>2.核心图表

<div id="servicesChart2"></div><div>3.带有<span class="code">颜色的材质图表:['red']</span></div><div id="servicesChart3"></div><div>4.多系列材料图表</div><div id="servicesChart4"></div>

I've created a google bar chart using the Google Visualization API and I'm trying to add a column which will be used for style. Here's my implementation below using the .addcolumn() and then adding the color field to each row, however each bar is still the default blue color.

<script type="text/javascript">
// Runs onload to build the first default chart and load the bar chart package
var jsonCoachCount;
window.onload = function(){
    jsonCoachCount = JSON.parse('[{"Service_Count":"4","Name":"Other"},  {"Service_Count":"4","Name":"Campus Network"},{"Service_Count":"3","Name":"Learn@UW"},{"Service_Count":"2","Name":"Customer Service"},{"Service_Count":"1","Name":"Blackboard Collaborate"},{"Service_Count":"1","Name":"Office 365"},{"Service_Count":"1","Name":"Multiple"},{"Service_Count":"1","Name":"Office-ionado"},{"Service_Count":"1","Name":"Case Notes"},{"Service_Count":"1","Name":"ResNet"}]');

// Load the Visualization API and the barchart package.
    google.charts.load('current', {'packages': ['bar']});
// Set a callback to run when the Google Visualization API is loaded.
    google.charts.setOnLoadCallback(drawChart);

};
function drawChart(){

    var servicesData = new google.visualization.DataTable();

    servicesData.addColumn('string', 'Service');
    servicesData.addColumn('number', 'Number of Coaches');
    servicesData.addColumn({type:'string', role:'style'});

    for(i = 0; i < jsonCoachCount.length; i++){
        tempArray =[];
        tempArray.push(String (jsonCoachCount[i]['Name']),
                parseInt(jsonCoachCount[i]['Service_Count']),
                'color:Red');
        servicesData.addRow(tempArray);
    }

    var options = {
        backgroundColor: {
            fill: '#E8E4D8'
        },
        legend: { position: 'none' },
        titleTextStyle:{
            bold: 'true'
        },
        chart: {
            title: 'Coaches by Service',
            subtitle: 'Coaches by Services: From 2016-09-10 until Today'
        },
        bar: {
            groupWidth: '60%'
        },
        'hAxis': {
            textStyle: {
                fontSize: 11
            }
        }
    };

    var chart = new google.charts.Bar(document.getElementById('servicesChart'));

    chart.draw(servicesData, google.charts.Bar.convertOptions(options));

}
<html>

<head>
<script type="text/javascript"     src="https://www.gstatic.com/charts/loader.js"></script>
</head>

<body>
</body>

</html>

I'm not sure where I'm going wrong or if I've misunderstood a piece of the documentation. I'd appreciate help for changing the color of the bars on my bar chart, thanks!

解决方案

each color in the colors option is applied to each series / y-axis column in the data table.
if there is only one y-axis column, only one color will be applied.

Otherwise, a Style Column Role is the easiest way to color an individual bar.
However, it does not work on Material Charts.

For options, see example charts...

If you are fine with each bar being the same color...

If you must have Material Chart with separate colors for each bar...

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

function init() {
  var jsonCoachCount = JSON.parse('[{"Service_Count":"4","Name":"Other"},  {"Service_Count":"4","Name":"Campus Network"},{"Service_Count":"3","Name":"Learn@UW"},{"Service_Count":"2","Name":"Customer Service"},{"Service_Count":"1","Name":"Blackboard Collaborate"},{"Service_Count":"1","Name":"Office 365"},{"Service_Count":"1","Name":"Multiple"},{"Service_Count":"1","Name":"Office-ionado"},{"Service_Count":"1","Name":"Case Notes"},{"Service_Count":"1","Name":"ResNet"}]');

  var options = {
      backgroundColor: {
          fill: '#E8E4D8'
      },
      legend: { position: 'none' },
      titleTextStyle:{
          bold: 'true'
      },
      chart: {
          title: 'Coaches by Service',
          subtitle: 'Coaches by Services: From 2016-09-10 until Today'
      },
      bar: {
          groupWidth: '60%'
      },
      hAxis: {
          textStyle: {
              fontSize: 11
          }
      }
  };

  drawChart();
  drawSeriesChart();

  function drawChart() {
      var servicesData = new google.visualization.DataTable();

      servicesData.addColumn('string', 'Service');
      servicesData.addColumn('number', 'Number of Coaches');
      servicesData.addColumn({type:'string', role:'style'});

      for (i = 0; i < jsonCoachCount.length; i++) {
          var tempArray =[];
          var tempColor;
          switch (i) {
            case 0:
              tempColor = 'color:Red';
              break;

            case 1:
              tempColor = 'orange';
              break;

            case 2:
              tempColor = 'fill-color: gold;';
              break;

            case 3:
              tempColor = 'bar {color: green;}';
              break;

            case 4:
              tempColor = 'bar {fill-color: blue;}';
              break;

            default:
              tempColor = 'bar {fill-color: cyan; stroke-color: black; stroke-width: 4;}';
          }
          tempArray.push(
            String (jsonCoachCount[i]['Name']),
            parseInt(jsonCoachCount[i]['Service_Count']),
            tempColor
          );
          servicesData.addRow(tempArray);
      }

      var chart = new google.charts.Bar(document.getElementById('servicesChart1'));
      chart.draw(servicesData, google.charts.Bar.convertOptions(options));

      var chart = new google.visualization.ColumnChart(document.getElementById('servicesChart2'));
      chart.draw(servicesData, options);

      // only one series exists -- only one color will work
      options.colors = ['red'];
      var chart = new google.charts.Bar(document.getElementById('servicesChart3'));
      chart.draw(servicesData, google.charts.Bar.convertOptions(options));
  }

  function drawSeriesChart() {
      var servicesData = new google.visualization.DataTable();

      servicesData.addColumn('string', 'Service');
      for (i = 0; i < jsonCoachCount.length; i++) {
        servicesData.addColumn('number', String (jsonCoachCount[i]['Name']));
        servicesData.addColumn('number', 'Spacer');
      }

      var tempArray = [];
      tempArray.push('Number of Coaches');
      for (i = 0; i < jsonCoachCount.length; i++) {
        tempArray.push(parseInt(jsonCoachCount[i]['Service_Count']));
        tempArray.push(null);
      }
      servicesData.addRow(tempArray);

      options.colors = [
        'deeppink',
        'red',
        'orange',
        'gold',
        'green',
        'blue',
        'indigo',
        'purple',
        'violet',
        'pink'
      ];

      var chart = new google.charts.Bar(document.getElementById('servicesChart4'));
      chart.draw(servicesData, google.charts.Bar.convertOptions(options));
  }
}
div {
  padding: 2px 0px 2px 0px;
  font-weight: bold;
}

.code {
  background-color: lightgray;
  font-family: Courier New;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div>1. Material Chart</div>
<div id="servicesChart1"></div>
<div>2. Core Chart</div>
<div id="servicesChart2"></div>
<div>3. Material Chart with <span class="code">colors: ['red']</span></div>
<div id="servicesChart3"></div>
<div>4. Multi-Series Material Chart</div>
<div id="servicesChart4"></div>

这篇关于Google 条形图无法更改单个条形颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 05:27