Home > Blockchain >  How to colorize individual rings in polar chart background in chart.js/ng2-charts?
How to colorize individual rings in polar chart background in chart.js/ng2-charts?

Time:01-12

I am trying to change the color of individual polar chart rings using chart.js version and ng2-charts in Angular but in the documentation of particular versions, I haven't found anything related to it and neither searching the solution on web.

"chart.js": "^2.8.0",
"ng2-charts": "^2.3.0",

Code:

  public polarAreaChartLabels: Label[] = [];

  public polarAreaChartData: SingleDataSet = [];

  public polarAreaLegend = true;

  myColors = [{ backgroundColor: ["#cb4b4b", "#edc240", "#afd8f8"] }];

  public polarAreaChartType: ChartType = "polarArea";

  public polarAreaChartOptions: ChartOptions = {
    plugins: {
      datalabels: {
         color: '#000000',
         anchor: 'end',
         align: 'end',
         padding: 50,
         display: true,
         font: {
           weight: 'bolder'
         },
         formatter: function(value, ctx) {
          return `${ctx.chart.data.labels[ctx.dataIndex]} - ${value} %`;
       },
      },
    },
    scale: {
      ticks: {
          beginAtZero: true,
          max: 100,
          min: 0,
          stepSize: 10
      }
    }
  };

  public ChartPlugins = [pluginDataLabels];

HTML:

            <canvas id="polar-chart" baseChart height="40vh" width="120vw" 
                [data]="polarAreaChartData" 
                [labels]="polarAreaChartLabels"
                [legend]="polarAreaLegend"
                [plugins]="ChartPlugins"
                [options]="polarAreaChartOptions"
                [chartType]="polarAreaChartType" 
                [colors]="myColors">        
            </canvas>

Current Output

Current Output

Desired Output

Desired Output

Is there any plugin or solution available for this? Any help would be much appriciated.

CodePudding user response:

This can be done by defining scale.gridLines.color option as an array of colors.

options: {
  scale: {
    gridLines: {
      color: [...]
    }
  }
}

Please take a look at the below runnable code and see how it works.

window.myChart = new Chart('canvas', {
  type: 'polarArea',
  data: {
    datasets: [{
      label: 'My Dataset',
      data: [4, 5, 4, 2, 6],
      backgroundColor: ['rgba(255, 159, 64, 0.2)', 'rgba(255, 205, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(153, 102, 255, 0.2)']
    }]
  },
  options: {
    scale: {
      gridLines: {
        color: ['black', 'orange', 'yellow', 'green', 'blue']
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>   
<canvas id="canvas"></canvas>

  •  Tags:  
  • Related