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

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

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

  1. let month_true = [
  2. {
  3. bob: {
  4. "base-certificate": 60,
  5. "case-certificate": 1,
  6. "standard-certificate": 7,
  7. },
  8. x: 9,
  9. },
  10. {
  11. bob: {
  12. "base-certificate": 30,
  13. "case-certificate": 4,
  14. "standard-certificate": 5,
  15. },
  16. x: 11,
  17. },
  18. ];

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

  1. function getDateOfWeek(w, y) {
  2. var d = 1 + (w - 1) * 7; // 1st of January + 7 days for each week
  3. return new Date(y, 0, d);
  4. }

通过数据进行Map:

  1. let newData = month_true.map(function (m) {
  2. let dateObject = new Date();
  3. let year = dateObject.getFullYear();
  4. const weekDate = getDateOfWeek(m.x, year);
  5. let r = new Date(Date.parse(weekDate));
  6. const newd = {
  7. x: r.setHours(0, 0, 0, 0),
  8. base: m.bob["base-certificate"],
  9. case: m.bob["case-certificate"],
  10. standard: m.bob["standard-certificate"],
  11. };
  12. return newd;
  13. });
  14. let newdate = newData.map(function (d) {
  15. return d.x;
  16. });

现在构建图表:

  1. let ctx = document.getElementById("chart").getContext("2d");
  2. let config = {
  3. //labels: newdate,
  4. type: "bar",
  5. data: {
  6. datasets: [
  7. {
  8. label: "base",
  9. data: newData,
  10. parsing: {
  11. xAxisKey: "x",
  12. yAxisKey: "base",
  13. },
  14. },
  15. {
  16. label: "Case",
  17. data: newData,
  18. parsing: {
  19. xAxisKey: "x",
  20. yAxisKey: "case",
  21. },
  22. },
  23. {
  24. label: "Standard",
  25. data: newData,
  26. parsing: {
  27. xAxisKey: "x",
  28. yAxisKey: "standard",
  29. },
  30. },
  31. ],
  32. },
  33. options: {
  34. scales: {
  35. x: {
  36. ticks: {
  37. beginAtZero: true,
  38. },
  39. offset: true,
  40. type: "time",
  41. time: {
  42. //isoWeekday: true,
  43. unit: "week",
  44. },
  45. },
  46. },
  47. },
  48. };
  49. let myChart = new Chart(ctx, config);

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

zpgglvta

zpgglvta1#

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

  1. options: {
  2. scales: {
  3. x: {
  4. type: 'time',
  5. ticks: {
  6. source: 'data'
  7. }
  8. }
  9. }
  10. }

相关问题