2017-03-06 93 views
0

我有一個圖表,我的x軸是一個時間軸,我需要根據我的數據動態更改時間軸。例如: 例如: 如果日期範圍(在我的數據中)很大,我需要我的座標軸來顯示月份,如果範圍小於日期。 我試圖讓它更清晰: 我有一個日期範圍:'09/07/2016' - '09/02/2016' - 我的軸需要根據天顯示我的數據。 但: 如果我的範圍是:'09/07/2016' - '09/02/2017'那麼我的軸需要顯示幾個月或四分之一,因爲這兩個日期之間的差距更大。 這是可能的和如何?在x軸上動態更改日期

+0

什麼你試過這麼遠嗎?你能分享一些代碼嘗試嗎?我認爲你必須更好地詳細說明你正在嘗試做什麼。 – VincenzoC

+0

以及我開始寫東西,但我想也許有一個現成的選項chart.js&moment.js .. – Damkulul

回答

0

根據chart.js API,Time Scale是您想要使用的。但是,縮放不會根據數據集中日期範圍的大小自動調整顯示格式。

你將不得不實現你自己的javascript函數,它將基於選定的數據改變你想要的尺度選項。這聽起來很有挑戰性,但如果你仔細想想它其實並非如此。實際上,由於您將爲用戶提供過濾數據的方法,因此您必須實現一個類似的功能,該功能將更改圖表中的基礎數據(在用戶設置過濾器之後),然後重新 - 繪製圖表(通過使用.update()原型方法實現)。

在這個相同的功能中,實現您的邏輯來確定合適的時間尺度顯示格式(基於您的數據跨度),並更新圖表刻度選項(在您致電.update()之前)。下面是一個例子。

假設你有一個類的.date-filter你的HTML某種日期範圍選擇框......

// initial chart definition 
var chart = new Chart($('#myChart'), { 
    type: 'line', 
    data: { 
    labels: [/* chart labels */], 
    datasets: [{ 
     data: { /* chart data */}, 
    }] 
    }, 
    options: { /* options...including time scale options */} 
}); 

// change handler on the date filter drop down which changes the chart data and time scale options 
$(".date-filter").change(function() { 
    var selectedRange = $(this).val(); 
    var parsedStartDate = // use selectedRange to parse start date 
    var parsedEndDate = // use selectedRange to parse end date 
    var dayMagnitude = // use moment.js to calculate difference in start/end in days 

    if (daysMagnitude < 30) { 
    // configure time scale displayFormat in terms of days 
    } else if (daysMagnitude < 90) { 
    // configure time scale displayFormat in terms of months 
    } else if (daysMagnitude < 180) { 
    // configure time scale displayFormat in terms of quarters 
    } 
    // ... 

    // update the underlying chart data by accessing the underlying dataset that you are modifying 
    chart.data.datasets[0].data = // new data object based on the filter criteria 

    // update the time scale options 
    chart.options.scales.yAxes = // updated time scale options 

    // re-render your chart 
    chart.update(); 
});