2017-03-06 8 views
0

私はチャートを持っています。私のx軸はタイムラインです。データに応じて動的にタイムラインを変更する必要があります。 例: 日付範囲(データ内)が大きい場合範囲が小さい場合は月を表示するよう軸を設定する必要があります。 悪いことを明確にしよう: 私は日付の範囲があります:'09/07/2016' - '09/02/2016' - 私の軸は日によってデータを表示する必要があります。 しかし: 私の範囲が:'09/07/2016' - '09/02/2017'の場合、これらの2つの日付の間のギャップが大きいので、私の軸は月または四半期を表示する必要があります。 それは可能でしょうか?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(); 
}); 
関連する問題