javascript - 我想改变条形图单个条的颜色

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

最佳答案

据我所知,您的问题主要与 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

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

$.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)";
  }
});

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

关于javascript - 我想改变条形图单个条的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55843497/

相关文章:

javascript - 可拖动始终位于最外层可排序

php - 我如何使用 css 对齐我的 div 容器

html - 图像上的标题属性在 Safari 中包裹在 A 标签中,没有工作?

php - PHP 中的变量未更新

javascript - Facebook 喜欢的页面(新 API)

javascript - 带有过滤器的 SVG 到 HTML5 Canvas 实现

javascript - 使用位置 : absolute; in CSS 时滚动条 "jerks"

javascript - 如何使用 XMLHTTPRequest 处理 CSRF token ?

javascript - Discord Bot 公告 channel

javascript - 如何在 jQuery 中推送、弹出和包装值?