Home > Software engineering >  Trying to get a certain color chart based on range in ApexCharts
Trying to get a certain color chart based on range in ApexCharts

Time:02-05

enter image description here

I want to change the color of the bar depending on a range the percentage falls into. I would also like to change the text "Culture Score" according to the same range.

// pseudocode
If % < 33: Color = Red & Text = "Poor"
If % < 66: Color = Yellow & Text = "Fair"
Else: Color = Green && Text = "Great"

Here is my chart options. I am using a Radial Bar chart from Apex Charts.

// Chart Options
var optionsRadial = {
 chart: {
     height: 350,
     type: 'radialBar',
 },
 series: [data.cultureScore],
 labels: ['Culture Score'],
 plotOptions: {
  radialBar: {
    startAngle: -135,
    endAngle: 135
  }
 }
}

I am using vanilla javascript too.

CodePudding user response:

You can use updateOptions() like so:

let options = {
  series: [75],
  chart: {
    type: 'radialBar',
    height: 350
  },
  labels: ['Great'],
  fill: {
    colors: ['#00ff00']
  },
  plotOptions: {
    radialBar: {
      startAngle: -135,
      endAngle: 225,
      dataLabels: {
        name: {
          offsetY: -10,
          color: '#888',
          fontSize: '17px'
        },
        value: {
          color: '#111',
          fontSize: '36px'
        }
      }
    }
  }
};

let chart = new ApexCharts(document.querySelector('#chart'), options);
chart.render();

setInterval(() => {
  let randomInt = Math.floor(Math.random() * 100),
      labels = [],
      fill = {};
  
  if (randomInt < 33) {
    labels.push('Poor');
    fill.colors = ['#ff0000'];
  } else if (randomInt < 66) {
    labels.push('Fair');
    fill.colors = ['#ffff00'];
  } else {
    labels.push('Great');
    fill.colors = ['#00ff00'];
  }
  
  chart.updateOptions({ series: [randomInt], labels, fill }); // <--- HERE
}, 3000);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/apexcharts.min.js"></script>

<div id="chart"></div>

  • Related