我在制作包含垂直和水平轴日期的Google Chart API折线图时遇到问题。生成的图表应如下所示:
这是一些试图产生这种效果的代码:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
google.load("visualization", "1", {packages:["LineChart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('date', 'Target');
data.addColumn('date', 'Results');
data.addRows([
[new Date(2015, 1 ,1), new Date(2015, 3 ,1),new Date(2015, 4 ,1)],
[new Date(2015, 3 ,1), new Date(2015, 4 ,1),new Date(2007, 4 ,15)],
]);
var options = {'vAxis': {format:'MMM d, y'}};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
// var chart = new google.visualization.AnnotatedTimeLine(document.getElementById('chart_div'));
// chart.draw(data, {displayAnnotations: true});
}
</script>
</head>
<body>
<div id="chart_div" style="width: 300px; height: 240px;" ></div>
</body>
</html>
但结果图表如下所示:
其中垂直轴显示的值与提供的日期值不对应。我尝试使用vAxis.format
选项设置,但没有任何效果。
想知道纵轴如何显示'2015年2月'等?感谢。
答案 0 :(得分:1)
由于您使用的是google.visualization.LineChart
,因此需要加载corechart
个包:
google.load("visualization", "1", { packages: ["corechart"] });
之后您可以指定日期类型值:
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('date', 'Target');
data.addColumn('date', 'Results');
data.addRows([
[new Date(2015, 6, 1), new Date(2016, 2 ,1), new Date(2015, 11 ,1)],
[new Date(2015, 7 ,1), new Date(2016, 1 ,1), new Date(2015, 11 ,1)],
[new Date(2015, 8 ,1), new Date(2015, 11 ,1), new Date(2015, 11 ,1)],
]);
示例强>
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('date', 'Target');
data.addColumn('date', 'Results');
data.addRows([
[new Date(2015, 6, 1), new Date(2016, 2 ,1), new Date(2015, 11 ,1)],
[new Date(2015, 7 ,1), new Date(2016, 1 ,1), new Date(2015, 11 ,1)],
[new Date(2015, 8 ,1), new Date(2015, 11 ,1), new Date(2015, 11 ,1)],
]);
var options = {
hAxis: {
format: 'MMM d, y',
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart_div" style="width: 480px; height: 320px;"></div>