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

mbjcgjjk  于 5个月前  发布在  Chart.js
关注(0)|答案(4)|浏览(74)

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

1tu0hz3e

1tu0hz3e1#

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

options: {
  scales: {
    xAxes: [{
      type: 'time',
      time: {
        displayFormats: {
           'millisecond': 'MMM DD',
           'second': 'MMM DD',
           'minute': 'MMM DD',
           'hour': 'MMM DD',
           'day': 'MMM DD',
           'week': 'MMM DD',
           'month': 'MMM DD',
           'quarter': 'MMM DD',
           'year': 'MMM DD',
        }
        ...

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

options: {
  scales: {
    xAxes: [{
      type: 'time',
      time: {
        unit: 'day',
        unitStepSize: 1,
        displayFormats: {
           'day': 'MMM DD'
        }
        ...


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

xqkwcwgp

xqkwcwgp2#

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

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

字符串

t8e9dugd

t8e9dugd3#

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

let xAxes = {
    type: "time",
    time: {
        displayFormats: {
            hour: "hA"
        }
    },
    display: true,
    ticks: {
        reverse: true
    },
    gridLines: { display: false }
}
// if more than two days between start and end of data,  set format to show date,  not hrs
if ((parseInt(Cookies.get("epoch_max")) - parseInt(Cookies.get("epoch_min"))) > (1000 * 60 * 60 * 24 * 2)) {
    xAxes.time.displayFormats.hour = "MMM D";
}

字符串

jk9hmnmh

jk9hmnmh4#

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

//convert the date to a standard format
var dt = new Date(date);
//take only the date and month and push them to your label array

$rootScope.charts.mainChart.labels.push(dt.getDate() + "-" + (dt.getMonth() + 1));

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

相关问题