我想更改条形图的各个条形的颜色

时间:2019-04-25 06:57:18

标签: javascript jquery html ajax chart.js

我正在使用php从mysql获取数据以填充数组,然后使用该结果填充图表数据。我想更改大于50的条的颜色。我尝试了一些已经在堆栈溢出中的示例,但是我无法解决问题。这就是为什么我现在要问这个问题。

$(document).ready(function() {
  $.ajax({
    url: "http://localhost:8080/chartjs/data.php",
    method: "GET",
    success: function(data) {
      console.log(data);
      var player = [];
      var score = [];

      for (var i in data) {
        player.push(data[i].y);

        score.push(data[i].x);
      }


      var chartdata = {
        labels: player,
        datasets: [{
            label: 'Records from mysql',
            backgroundColor: 'rgb(92, 95, 102)',
            borderColor: 'rgba(200, 200, 200, 0.75)',
            hoverBackgroundColor: 'rgba(30, 0, 200)',
            hoverBorderColor: 'rgba(200, 200, 197)',
            data: score
          }

        ]
      };



      var ctx = $("#mycanvas");

      var barGraph = new Chart(ctx, {
        type: 'bar',
        colors: {
          data: function(score) {
            return (score.value >= 45) ? '#00ff00' : '#f90411';
          }
        },
        data: chartdata
      });
    },
    error: function(data) {
      console.log(data);
    }

  });
});
#chart-container {
  width: 640px;
  height: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<div id="chart-container">
  <canvas id="mycanvas"></canvas>
</div>

1 个答案:

答案 0 :(得分:1)

据我所知,您的问题主要与chart.js的用法有关。我为您解决的问题的解决方案如下所示:

//Load your data (obviously this is a hardcoded example, you could use any backend code like PHP):
let data = [12, 19, 74, 38, 45, 62];
//Insantiate fields you would like to use, such as `colors` for background color and `borderColors` for, you guessed it, the color of the borders:
let colors = [];
let borderColors = [];
//Set the field values based on value (this would be your logic):
$.each(data, function(index, value) {
  //When the value is higher than 45, set it to given color, else make them the other color (in the example the bars would appear red-ish):
  if(value > 45) {
    colors[index] = "rgba(0, 255, 0, 0.2)";
    borderColors[index] = "rgba(0, 255, 1)";
  }
  else {
    colors[index] = "rgba(249, 4, 17, 0.2)";
    borderColors[index] = "rgba(249, 4, 17, 1)";
  }
});

//Any code related to creating the chart with the bars (you could find any documentation regarding this code on the homepage of Chart.js):
let ctx = document.getElementById('myChart');
let myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['1', '2', '3', '4', '5', '6'],
        datasets: [{
            label: 'Records from mysql',
            //Populate your fields here:
            data: data,
            backgroundColor: colors,
            borderColor: borderColors,
            hoverBackgroundColor: 'rgba(30, 0, 200)',
            hoverBorderColor: 'rgba(200, 200, 197)',
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
});
#chart-container {
  width: 640px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<div id="chart-container">
  <canvas id="myChart"></canvas>
</div>

JSFiddle

我在Github上的following post上应用了一些代码:

$.each(data, function(index, value) {
  //When the value is higher than 45, set it to given color, else make them the other color (in the example the bars would appear red-ish):
  if(value > 45) {
    colors[index] = "rgba(0, 255, 0, 0.2)";
    borderColors[index] = "rgba(0, 255, 1)";
  }
  else {
    colors[index] = "rgba(249, 4, 17, 0.2)";
    borderColors[index] = "rgba(249, 4, 17, 1)";
  }
});

如果有人知道更干净的解决方案,请在评论中让我知道。