javascript 如何使用条件更改chart.js中图表的背景

1l5u6lss  于 2022-11-27  发布在  Java
关注(0)|答案(1)|浏览(134)

我使用Chart.js创建图表的垂直条。我想显示3个开发人员在特定时间内开发的代码数量。我想通过三种不同的颜色来区分这三个开发人员。就像这样...

import { Chart } from "chart.js/auto";

(async function () {
const data = [
{
  filename: "center.js",
  developer: ["John"],
  lastedit: "01-01-2022",
  lines: [40],
 },
 {
  filename: "collide.js",
  developer: ["Alex"],
  lastedit: "15-02-2022",
  lines: [70],
  },
  {
  filename: "constant.js",
  developer: ["Bob"],
  lastedit: "25-02-2022",
  lines: [10],
  },
  {
  filename: "index.js",
  developer: ["Alex"],
  lastedit: "17-03-2022",
  lines: [8],
  },
  {
  filename: "jiggle.js",
  developer: ["Bob"],
  lastedit: "19-03-2022",
  lines: [5],
  },
  {
  filename: "link.js",
  developer: ["Bob", "Alex", "John"],
  lastedit: "29-03-2022",
  lines: [120],
  },
  {
  filename: "manyBody.js",
  developer: ["Bob", "John"],
  lastedit: "09-04-2022",
  lines: [180],
  },
  {
  filename: "simulation.js",
  developer: ["Alex", "Bob", "John"],
  lastedit: "01-05-2022",
  lines: [140],
  },
  {
  filename: "x.js",
  developer: ["Bob"],
  lastedit: "03-05-2022",
  lines: [80],
  },
  ];

 new Chart(document.getElementById("acquisitions"), {
  type: "bar",
  data: {
    labels: data.map((row) => row.lastedit),
    datasets: [
    {
      label: "The amount of codes",

      data: data.map((row) => row.lines),

      backgroundColor: ["#f38b4a", "#56d798", "#6970d5"],
    },
    ],
   },
   });
  })();

我的目标是,此图表中每个条形的颜色可以根据3个不同的开发人员名称而变化。那么,我们如何为背景颜色提供一个假设?

btxsgosb

btxsgosb1#

backgroundColor不是字符串数组,而只是字符串。

backgroundColor: "#f38b4a".

Dataset也是对象的数组,它应该代表每个开发人员的数据集。

var barChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: data.map((row) => row.lastedit),
    datasets: [{
      label: 'Alex',
      data: [12, 19, 3, 17, 28, 24, 7],
      backgroundColor: "rgba(255,0,0,1)"
    }, {
      label: 'Bob',
      data: [30, 29, 5, 5, 20, 3, 10],
      backgroundColor: "rgba(0,0,255,1)"
    },
    {
      label: 'John',
      data: [30, 29, 5, 5, 20, 3, 10],
      backgroundColor: "rgba(255,0,255,1)"
    }]
  }
});

data:[12,19,3,17,28,24,7] =〉这是一个行编辑数组,假设Alex每天都做了编辑,索引表示天数,索引值表示Alex编辑的行。
假设在第2天(索引1或日期:15-02-2022如图所示)Alex写了19行代码。
此代码段应返回类似于x1c 0d1x的内容

相关问题