如何在Chart.js v2中格式化x轴时间刻度值

mbjcgjjk  于 2024-01-07  发布在  Chart.js
关注(0)|答案(4)|浏览(290)

当我通过options.scales.xAxes.time.tooltipFormat悬停在折线图上的数据点上时,我可以格式化工具提示,但我似乎不能为x轴刻度标签做这件事。我的data.labels是一个矩对象数组。它们显示为"MMM DD, YYYY"(例如,Feb 23,2012),但我想删除年份。

1tu0hz3e

1tu0hz3e1#

只需将所有选定时间单位的displayFormat设置为MMM DD

  1. options: {
  2. scales: {
  3. xAxes: [{
  4. type: 'time',
  5. time: {
  6. displayFormats: {
  7. 'millisecond': 'MMM DD',
  8. 'second': 'MMM DD',
  9. 'minute': 'MMM DD',
  10. 'hour': 'MMM DD',
  11. 'day': 'MMM DD',
  12. 'week': 'MMM DD',
  13. 'month': 'MMM DD',
  14. 'quarter': 'MMM DD',
  15. 'year': 'MMM DD',
  16. }
  17. ...

字符串
请注意,我已经将所有单位的显示格式设置为MMM DD

  1. options: {
  2. scales: {
  3. xAxes: [{
  4. type: 'time',
  5. time: {
  6. unit: 'day',
  7. unitStepSize: 1,
  8. displayFormats: {
  9. 'day': 'MMM DD'
  10. }
  11. ...


小提琴-http://jsfiddle.net/prfd1m8q/

展开查看全部
xqkwcwgp

xqkwcwgp2#

根据Chartjs文档页面tick配置部分。您可以使用回调函数格式化每个tick的值。例如,我想将显示日期的区域设置更改为始终为德语。在轴选项的tick部分中

  1. ticks: {
  2. callback: function(value) {
  3. return new Date(value).toLocaleDateString('de-DE', {month:'short', year:'numeric'});
  4. },
  5. },

字符串

t8e9dugd

t8e9dugd3#

我有一个不同的用例,我想要不同的格式,基于图表中数据的开始和结束时间之间的间隔。

  1. let xAxes = {
  2. type: "time",
  3. time: {
  4. displayFormats: {
  5. hour: "hA"
  6. }
  7. },
  8. display: true,
  9. ticks: {
  10. reverse: true
  11. },
  12. gridLines: { display: false }
  13. }
  14. // if more than two days between start and end of data, set format to show date, not hrs
  15. if ((parseInt(Cookies.get("epoch_max")) - parseInt(Cookies.get("epoch_min"))) > (1000 * 60 * 60 * 24 * 2)) {
  16. xAxes.time.displayFormats.hour = "MMM D";
  17. }

字符串

展开查看全部
jk9hmnmh

jk9hmnmh4#

你可以在将日期添加到数组中之前格式化它们。这就是我所做的。我使用AngularJS

  1. //convert the date to a standard format
  2. var dt = new Date(date);
  3. //take only the date and month and push them to your label array
  4. $rootScope.charts.mainChart.labels.push(dt.getDate() + "-" + (dt.getMonth() + 1));

字符串
在图表演示中使用此数组

相关问题