我有http://goodandevilbook.com/stats页面,我使用谷歌图表来显示数据。
在其中一个图表(面积图)上当我将鼠标悬停在工具提示上时,它会以难以阅读的格式显示日期。我想将此日期格式化为更易读的方式。此外,工具提示会显示ga:visitor,我想将其更改为访问者。我无法将JSON文件数据真正放入所需的格式,因为这是自动生成的
不知何故,我收到后需要更改这些数据。这是我生成区域图的代码:
google.setOnLoadCallback(drawGraph);
function drawGraph(){
var graph = new google.visualization.ChartWrapper({
"containerId":"last30chart",
"dataSourceUrl":"http://good-and-evil-stats.appspot.com/query?id=ahVzfmdvb2QtYW5kLWV2aWwtc3RhdHNyFQsSCEFwaVF1ZXJ5GICAgICA14wKDA&format=data-table-response",
"refreshInterval":0,
"chartType":"AreaChart",
"options":{
"width":675,
"height":400,
"chartArea":{width:"95%", height:"83%"},
"areaOpacity":0.1,
"pointSize":4,
"backgroundColor":"transparent",
"colors":['#76BB72'],
"legend":{position: 'none'},
"tooltip":{textStyle: {fontSize:18}},
"hAxis":{textPosition:"none", gridlines: {color: 'red', count: 7}},
"dateFormat":{formatType: "long"}
}
});
graph.draw();}
我试图插入用于格式化日期的代码。
https://developers.google.com/chart/interactive/docs/reference#dateformatter
这就是我在玩的东西:
var monthYearFormatter = new google.visualization.DateFormat({
pattern: "MMM yyyy"
});
monthYearFormatter.format(dataSourceUrl);
我已经尝试了很长一段时间,并且无法让它发挥作用。我是Javascript / jquery的新手,所以我不确定我在做什么。
答案 0 :(得分:2)
使用ChartWrapper对象的dataSourceUrl
参数提取数据时,无法格式化数据。您必须切换到使用Query对象,然后您可以根据需要格式化数据并更改列标签。由于您的日期实际上是字符串而不是Date对象,因此您必须使用DataView将它们转换为Date对象,然后才能对其进行格式化。这是一个例子:
function drawGraph(){
var query = new google.visualization.Query("http://good-and-evil-stats.appspot.com/query?id=ahVzfmdvb2QtYW5kLWV2aWwtc3RhdHNyFQsSCEFwaVF1ZXJ5GICAgICA14wKDA&format=data-table-response");
query.send(function (response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
// set the label of column 1 to "Visitors"
data.setColumnLabel(1, 'Visitors');
// create a formatter for the dates
var formatter = new google.visualization.DateFormat({pattern: "MMM yyyy"});
var graph = new google.visualization.ChartWrapper({
"containerId": "last30chart",
"chartType":"AreaChart",
dataTable: data,
"options": {
"width":675,
"height":400,
"chartArea": {width:"95%", height:"83%"},
"areaOpacity":0.1,
"pointSize":4,
"backgroundColor":"transparent",
"colors":['#76BB72'],
"legend":{position: 'none'},
"tooltip":{textStyle: {fontSize:18}},
"hAxis":{textPosition:"none", gridlines: {color: 'red', count: 7}},
"dateFormat":{formatType: "long"}
},
view: {
columns: [{
type: 'date',
label: data.getColumnLabel(0),
calc: function (dt, row) {
var dateStr = dt.getValue(row, 0);
var year = parseInt(dateStr.substring(0, 4), 10);
var month = parseInt(dateStr.substring(4, 6), 10) - 1; // convert month to 0-based index
var day = parseInt(dateStr.substring(6, 8), 10);
var date = new Date(year, month, day);
return {v: date, f: formatter.formatValue(date)};
}
}, 1]
}
});
graph.draw();
});
}