[英]How to group Json data based on Month and plot it using google chart
我使用谷歌圖表插件繪制區域圖表,通過使用JSON數據顯示如下代碼,其中包含值和圖表的日期應根據月份打印。
鏈接顯示在圖像中輸入圖像描述
如何使用谷歌圖表繪制基於月份的圖表
是否可以使用谷歌圖表buit功能,並需要為該achive編寫一些自定義的JavaScript?
<script type="text/javascript"> google.charts.load('current', { 'packages': ['corechart'] }); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Date', 'value'], [ "1/Jan/2017", 28 ], [ "5/Feb/2019", 174 ], [ "8/Mar/2017", 150 ], [ "2/Apr/2019", 174 ], [ "18/May/2019", 100 ], [ "22/Jun/2019", 5 ], [ "30/Jul/2019", 178 ], [ "28/Aug/2019", 59 ], [ "1/Sep/2019", 87 ], [ "10/Oct/2019", 50 ], [ "15/Nov/2019", 123 ], [ "20/Dec/2019", 108 ] ]); var options = { title: 'Company Performance', hAxis: { title: 'Date', titleTextStyle: { color: '#333' } }, curveType: 'function', legend: { position: 'bottom' }, pointSize: 5, dataOpacity: 0.5, vAxis: { minValue: 0 } }; var chart = new google.visualization.AreaChart(document.getElementById('chart_div')); chart.draw(data, options); } </script>
<div id="chart_div" style="width: 100%; height: 500px;"></div>
為了將x軸格式化為日期,
需要將數據表中的第一列從字符串轉換為實際日期...
我們可以使用帶有計算列的數據視圖來轉換日期...
var view = new google.visualization.DataView(data);
view.setColumns([{
type: 'date',
label: 'Date',
calc: function (dt, row) {
return new Date(dt.getValue(row, 0));
}
}, 1]);
此外,由於數據不按日期排序,我們可以將視圖轉換回數據表並對其進行排序......
data = view.toDataTable();
data.sort([{column: 0}]);
請參閱以下工作代碼段...
google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Date', 'value'], [ "1/Jan/2017", 28 ], [ "5/Feb/2019", 174 ], [ "8/Mar/2017", 150 ], [ "2/Apr/2019", 174 ], [ "18/May/2019", 100 ], [ "22/Jun/2019", 5 ], [ "30/Jul/2019", 178 ], [ "28/Aug/2019", 59 ], [ "1/Sep/2019", 87 ], [ "10/Oct/2019", 50 ], [ "15/Nov/2019", 123 ], [ "20/Dec/2019", 108 ] ]); var view = new google.visualization.DataView(data); view.setColumns([{ type: 'date', label: 'Date', calc: function (dt, row) { return new Date(dt.getValue(row, 0)); } }, 1]); data = view.toDataTable(); data.sort([{column: 0}]); var options = { chartArea: {bottom: 56}, title: 'Company Performance', hAxis: {format: 'MMM', title: 'Date', titleTextStyle: {color: '#333'} }, curveType: 'function', legend: { position: 'bottom'}, pointSize: 5, dataOpacity: 0.5, vAxis: {minValue: 0} }; var chart = new google.visualization.AreaChart(document.getElementById('chart_div')); chart.draw(data, options); }
<script src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.