我正在使用google chart插件通过使用JSON数据(如下面的代码所示)绘制面积图,其中包含值和图表中的日期应基于月份进行打印。
链接显示在图片中 enter image description here
如何使用Google图表根据月份绘制图表
是否可以使用Google Charts Buit的功能来做到这一点,并且需要为此实现编写一些自定义的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>
答案 0 :(得分:1)
为了将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>