X轴上的标签在Chart.js中未完全显示

mmvthczy  于 2022-11-07  发布在  Chart.js
关注(0)|答案(1)|浏览(247)

我有一个来自后端的数据(flak-sqlalchemy with mysql),其中数据包含整数形式的周、月和年的日期,看起来像这样:
在这种情况下,X表示一年中的星期:

let month_true = [
  {
    bob: {
      "base-certificate": 60,
      "case-certificate": 1,
      "standard-certificate": 7,
    },
    x: 9,
  },
  {
    bob: {
      "base-certificate": 30,
      "case-certificate": 4,
      "standard-certificate": 5,
    },
    x: 11,
  },
];

我做的第一件事是Map数据,并使用一个函数将x转换为Javascript和chart.js可读的格式,该函数将一年中的星期数转换为实际日期:
函数:

function getDateOfWeek(w, y) {
      var d = 1 + (w - 1) * 7; // 1st of January + 7 days for each week

      return new Date(y, 0, d);
    }

通过数据进行Map:

let newData = month_true.map(function (m) {
  let dateObject = new Date();
  let year = dateObject.getFullYear();
  const weekDate = getDateOfWeek(m.x, year);

  let r = new Date(Date.parse(weekDate));
  const newd = {
    x: r.setHours(0, 0, 0, 0),
    base: m.bob["base-certificate"],
    case: m.bob["case-certificate"],
    standard: m.bob["standard-certificate"],
  };
  return newd;
});

let newdate = newData.map(function (d) {
  return d.x;
});

现在构建图表:

let ctx = document.getElementById("chart").getContext("2d");
let config = {
  //labels: newdate,
  type: "bar",
  data: {
    datasets: [
      {
        label: "base",
        data: newData,
        parsing: {
          xAxisKey: "x",
          yAxisKey: "base",
        },
      },
      {
        label: "Case",
        data: newData,
        parsing: {
          xAxisKey: "x",
          yAxisKey: "case",
        },
      },
      {
        label: "Standard",
        data: newData,
        parsing: {
          xAxisKey: "x",
          yAxisKey: "standard",
        },
      },
    ],
  },
  options: {
    scales: {
      x: {
        ticks: {
          beginAtZero: true,
        },
        offset: true,
        type: "time",
        time: {
          //isoWeekday: true,
          unit: "week",
        },
      },
    },
  },
};

let myChart = new Chart(ctx, config);

已绘制,但X轴未显示第二个标签:
enter image description here
我怎样做才能使标签完整地显示出来?

zpgglvta

zpgglvta1#

这是因为默认情况下,时间刻度会自动生成刻度,如果您不想包含数据中的标签,则需要设置刻度。数据源:

options: {
  scales: {
    x: {
      type: 'time',
      ticks: {
        source: 'data'
      }
    }
  }
}

相关问题