如何在 Chart.js v2 中格式化 x 轴时间刻度值 [英] How to format x-axis time scale values in Chart.js v2

查看:25
本文介绍了如何在 Chart.js v2 中格式化 x 轴时间刻度值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我通过 options.scales.xAxes.time.tooltipFormat 将鼠标悬停在折线图上的数据点上时,我能够格式化工具提示,但我似乎无法为 x-轴刻度标签.我的 data.labels 是一个矩对象数组.它们显示为 "MMM DD, YYYY"(例如 2012 年 2 月 23 日),但我想放弃年份.

I am able to format the tooltips when I hover over a datapoint on a line chart via options.scales.xAxes.time.tooltipFormat, but I can't seem to do it for the x-axis tick lables. My data.labels is an array of moment objects. They display as "MMM DD, YYYY" (e.g. Feb 23, 2012), but I want to drop the year.

推荐答案

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

Just set all the selected time unit's displayFormat to 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.如果您可以控制数据范围和图表大小,更好的方法是强制一个单位,就像这样

Notice that I've set all the unit's display format to MMM DD. A better way, if you have control over the range of your data and the chart size, would be force a unit, like so

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

<小时>

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

这篇关于如何在 Chart.js v2 中格式化 x 轴时间刻度值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆