2016-09-16 79 views
0

如何在chartjs 2.0中隱藏x軸的值?你會注意到圖表超過了-60分。 x軸使用時間刻度,我設置了最大值和最小值。如何在chartjs 2.0中隱藏x軸的值?

enter image description here

這裏是我的圖表配置:

{ 
    "type":"line", 
    "data":{ 
     "datasets":[ 
     { 
      "label":"Scatter Dataset", 
      "data":[ 
       { 
        "x":"2016-09-16T16:36:53Z", 
        "y":88.46153846153845 
       }, 
       ... 
       { 
        "x":"2016-09-16T16:37:54Z", 
        "y":88.3076923076923 
       } 
      ], 
      "pointRadius":0, 
      "backgroundColor":"rgba(0,0,255,0.5)", 
      "borderColor":"rgba(0,0,255,0.7)" 
     } 
     ] 
    }, 
    "options":{ 
     "title":{ 
     "display":true, 
     "text":"Water Level Over Last 60 Seconds" 
     }, 
     "animation":false, 
     "scales":{ 
     "xAxes":[ 
      { 
       "type":"time", 
       "position":"bottom", 
       "display":true, 
       "time":{ 
        "max":"2016-09-16T16:37:54Z", 
        "min":"2016-09-16T16:36:54.000Z", 
        "unit":"second", 
        "unitStepSize":5 
       }, 
       "ticks":{ 
         callback: function(value, index, values) { 
          return "-" + (60 - 5 * index); 
         } 
       } 
      } 
     ], 
     "yAxes":[ 
      { 
       "display":true, 
       "ticks":{ 

       } 
      } 
     ] 
     }, 
     "legend":{ 
     "display":false 
     } 
    } 
} 

回答

2

可以使用Chart.js plugins實現這一目標。他們讓您處理創建,更新或繪製圖表時發生的事件。

在這裏,你將需要影響圖表被初始化之前:

// We first create the plugin 
var cleanOutPlugin = { 

    // We affect the `beforeInit` event 
    beforeInit: function(chart) { 

     // Replace `ticks.min` by `time.min` if it is a time-type chart 
     var min = chart.config.options.scales.xAxes[0].ticks.min; 
     // Same here with `ticks.max` 
     var max = chart.config.options.scales.xAxes[0].ticks.max; 

     var ticks = chart.config.data.labels; 
     var idxMin = ticks.indexOf(min); 
     var idxMax = ticks.indexOf(max); 

     // If one of the indexes doesn't exist, it is going to bug 
     // So we better stop the program until it goes further 
     if (idxMin == -1 || idxMax == -1) 
      return; 

     var data = chart.config.data.datasets[0].data; 

     // We remove the data and the labels that shouldn't be on the graph 
     data.splice(idxMax + 1, ticks.length - idxMax); 
     data.splice(0, idxMin); 
     ticks.splice(idxMax + 1, ticks.length - idxMax); 
     ticks.splice(0, idxMin); 
    } 
}; 

// We now register the plugin to the chart's plugin service to activate it 
Chart.pluginService.register(cleanOutPlugin); 

插件基本上是通過數據的循環,除去不應該顯示的值。

你可以看到這個插件工作在live example on jsFiddle

例如,設置爲2一分鐘,最多要6下面聊天......

enter image description here

...應該給出如下結果:

enter image description here