Angular - ChartJS -条形图-第一个标签未显示在X轴中

r3i60tvu  于 2023-04-06  发布在  Chart.js
关注(0)|答案(1)|浏览(198)

我尝试使用chartJS和Angular绘制一个条形图。为此,我对X轴值进行分组,以便它只显示年份。

但是我每次都错过了第一年。这意味着在上面的场景中,我有2022年和2023年的记录,但图表只显示2023年。
这种行为背后的原因是我没有2022年1月1日的数据。但我需要将2022也作为X轴的标签。我已经尝试添加bounds: 'ticks',但它在左侧和右侧显示空白(考虑到2022年的第一天)

是否有任何选项显示标签不包括空格?任何帮助,你可以提供将不胜感激。

xoshrz7s

xoshrz7s1#

一个可能的解决方案是将time.unit设置为"month",并使用ticks.callback使每年除第一个标签外的所有标签无效(return '')。
下面是一个非React代码片段,它说明了这个想法:

  1. const nPoints = 366,
  2. t0 = Date.now()-366*24*3600*1000,
  3. dt = 24*3600*1000;
  4. const ctx = document.getElementById('canvasChart').getContext("2d");
  5. let data = Array.from(
  6. {length: nPoints},
  7. (_, i)=>({
  8. datetime: t0 + dt*i,
  9. value: 10+4*Math.sin(i*Math.PI*3/nPoints)+
  10. 3*Math.random() + (Math.random() < 0.05 ? 5*Math.random() : 0)
  11. })
  12. );
  13. const yearsWithLabel = [];
  14. const config = {
  15. type: 'bar',
  16. data: {
  17. datasets:[{
  18. data,
  19. borderWidth: 1
  20. }]
  21. },
  22. options: {
  23. parsing: {
  24. xAxisKey: 'datetime',
  25. yAxisKey: 'value'
  26. },
  27. scales:{
  28. x:{
  29. type: 'time',
  30. grid:{
  31. display: false
  32. },
  33. ticks:{
  34. maxRotation: 0,
  35. callback(val, index){
  36. if(index === 0){
  37. yearsWithLabel.splice(0);
  38. }
  39. const date = new Date(val),
  40. yr = date.getFullYear();
  41. if(yearsWithLabel.includes(yr)){
  42. // if there's already a label for this year
  43. return '';
  44. }
  45. yearsWithLabel.push(yr);
  46. // you may want to add the month, otherwise one may think
  47. // the interval between the labels 2022 and 2023 is one year:
  48. // return date.toLocaleDateString(undefined, {year: 'numeric', month: "short"})
  49. return date.toLocaleDateString(undefined, {year: 'numeric'})
  50. }
  51. },
  52. time: {
  53. unit: 'month',
  54. }
  55. }
  56. },
  57. plugins: {
  58. legend:{
  59. display: false
  60. }
  61. }
  62. },
  63. };
  64. new Chart(ctx, config);
  1. <div style="width:90vw;height:90vh">
  2. <canvas id="canvasChart" ></canvas>
  3. </div>
  4. <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  5. <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns"></script>
展开查看全部

相关问题