Chart.js对于混合图(阶梯图和条形图),如何让每个阶梯从条形图的开始处开始,而不是从堆叠条形图的中间开始?

zour9fqk  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(309)

我试图删除条形图的偏移(偏移:false),但结果是第一个条形向左移动,因此只显示了第一个条形的一半。下面是我得到的结果,但没有显示阶梯图的开头和结尾。

  1. function createBarChart() {
  2. const ctx = document.getElementById('myChart');
  3. const myChart = new Chart(ctx, {
  4. type: 'line',
  5. data: {
  6. labels: ['1', '2', '3', '4', '5', '6'],
  7. datasets: [
  8. {
  9. type: 'line',
  10. label: 'Dataset 1',
  11. data: [18, 19, 16, 12, 13, 11],
  12. borderColor: 'rgb(54, 162, 235)',
  13. fill: false,
  14. radius: 0,
  15. stepped: 'middle',
  16. // xAxisID: 'xStepChart'
  17. },
  18. {
  19. type: 'bar',
  20. label: 'Label 2',
  21. data: [9.35, 8.35, 8.56, 6.46, 5.04, 3.15],
  22. //-- No gaps between bars
  23. barPercentage: 1.0,
  24. categoryPercentage: 1.0,
  25. backgroundColor: ['#71797E'],
  26. borderColor: ['#000000'],
  27. borderWidth: 1
  28. },
  29. {
  30. type: 'bar',
  31. label: 'Label 3',
  32. data: [20.34, 17.31, 16.39, 13.48, 11.29, 11.23],
  33. //-- No gaps between bars
  34. barPercentage: 1.0,
  35. categoryPercentage: 1.0,
  36. backgroundColor: ['#A9A9A9'],
  37. borderColor: ['#000000'],
  38. borderWidth: 1
  39. },
  40. {
  41. type: 'bar',
  42. label: 'Label 4',
  43. data: [20.40, 18.57, 16.96, 14.19, 12.68, 11.98],
  44. //-- No gaps between bars
  45. barPercentage: 1.0,
  46. categoryPercentage: 1.0,
  47. backgroundColor: ['rgba(46, 142, 201, 0.2)'],
  48. borderColor: ['rgba(61, 61, 60, 1)'],
  49. borderWidth: 1
  50. },
  51. ]
  52. },
  53. options: {
  54. scales: {
  55. x: {
  56. stacked: true,
  57. },
  58. y: {
  59. stacked: false
  60. }
  61. }
  62. }
  63. })
  64. }

enter image description here

pieyvz9o

pieyvz9o1#

您可以将'line'data定义为点数组(个别对象各有xy属性)。然后将dataset链接至第二个未显示的x轴。

  1. {
  2. type: 'line',
  3. label: 'Dataset 1',
  4. data: [{x: 0, y: 18}, {x: 1, y: 19}, {x: 2, y: 16}, {x: 3, y: 12}, {x: 4, y: 13}, {x: 5, y: 11}, {x: 6, y: 11}],
  5. ...
  6. stepped: 'end',
  7. xAxisID: 'x2'
  8. },

X轴为'line'dataset ...

  1. x2: {
  2. type: 'linear',
  3. display: false
  4. }

请看一下下面修改后的可运行代码,看看它是如何工作的。
第一个
如果您有更多的数据点,您可能还必须定义x2.max,以保持datasets同步(显示下面的代码片段)。
第一个

展开查看全部

相关问题