ChartJS:如何将月线图与日线图居中?

ChartJS: How to center monthly bars against a daily line chart?

我正在尝试显示每月总销售额和每日库存水平。这样您就可以很容易地看到您在某个特定月份没有任何销售,因为您的库存不足。每月销售额是一个条形图,应该位于每个月的中心(在刻度线之间)。

为了让它靠近中间,我的数据使用每个月的 15 日作为居中日期。我想知道是否有更好的方法来实现这个?

可玩的 JSFiddle:https://jsfiddle.net/8Lydhpqc/3/

const dailyStock = [
  { x: "2017-08-02", y: 1 },
  { x: "2017-08-25", y: 3 },
  { x: "2017-09-10", y: 7 },
  { x: "2017-09-28", y: 0 },
  { x: "2017-10-02", y: 3 },
  { x: "2017-10-24", y: 2 },
  { x: "2017-11-01", y: 1 },
  { x: "2017-11-30", y: 0 },
];

//using the 15th of each month to center it
const monthlyTotal = [
  { x: "2017-08-15", y: 1 },
  { x: "2017-09-15", y: 10 },
  { x: "2017-10-15", y: 5 },
  { x: "2017-11-15", y: 5 },
];


var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
  type: "bar",
  data: {
    labels: ["2017-08", "2017-09", "2017-10", "2017-11"],
    datasets: [
      {
        label: "sales",
        data: data,
        backgroundColor: "green",
        borderColor: "black",
        borderWidth: 1,
        order: 2,
      },
      {
        label: "stock",
        type: "line",
        data: dailyStock,
        backgroundColor: "orange",
        borderColor: "orange",
        fill: false,
        order: 1,
      },
    ],
  },
  options: {
    scales: {
      xAxes: [
        {
          type: "time",
          time: {
            unit: "month",
            displayFormats: {
              month: "MMM",
            },
          },
          distribution: "linear",
          },
      ],
      yAxes: [
        {
          ticks: {
            beginAtZero: true,
          },
        },
      ],
    },
  },
});

欢迎使用 Whosebug!

看来还有比15号更好的办法

您需要为类别类型轴添加另一个轴。同样重要的是,您在该轴上也有“offset: true”。否则不居中

在下面的代码中,我将该类别命名为“bar”,将现有的类别命名为“line”

我还创建了一个fiddle:https://jsfiddle.net/jyf8ax3e/

var myChart = new Chart(ctx, {
  type: "bar",
  data: {
    labels: ["2017-08", "2017-09", "2017-10", "2017-11"],
    datasets: [
      {
        barPercentage: .7,
        xAxisID: "bar",
        label: "sales",
        data: monthlyTotal,
        backgroundColor: "green",
        borderColor: "black",
        borderWidth: 1,
        width: 55,
        order: 2,
      },
      {
        label: "stock",
        type: "line",
        data: dailyStock,
        backgroundColor: "orange",
        borderColor: "orange",
        fill: false,
        order: 1,
      },
    ],
  },
  options: {
    scales: {
      xAxes: [
        {
            id: "line",
          type: "time",
          time: {
            unit: "month",
            displayFormats: {
              month: "MMM",
            },
          },
          distribution: "linear",
          },
          {
            id: "bar",
          offset: true,
          type: "category",
          distribution: "series",
          }
      ],
      yAxes: [
        {
          ticks: {
            beginAtZero: true,
          },
        },
      ],
    },
  },
});