1
我非常喜歡將ChartJs作爲JavaScript庫,並且在製作分組條形圖時遇到了一些困難,這些分組條形圖可以讀取每個JSON對象,並將其作爲自己的勾號放置在X軸上。分組條形圖ChartJS
這真的很難解釋,但我想以星期一的JSON對象爲例,我想在X軸上顯示星期一以及我希望作爲分組條形圖出現在圖表上的所有內容(我希望original_tweet,轉推等)。
但是現在它只是複製它。
的index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div style="width: 100%; height: 100%;">
<canvas id="myChart" style="width: 100%; height: auto;"></canvas>
</div>
<div id="js-legend" class="chart-legend"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.1/Chart.min.js"></script>
<script src="js/chartJsControl.js"></script>
</body>
</html>
chartJsControl.js:
$.getJSON("data.json", function (json) {
// will generate array with ['Monday', 'Tuesday', 'Wednesday']
var labels = json.map(function (item) {
return item.timestamp;
});
var tweet = json.map(function (item) {
return item.original_tweet;
});
var data = {
labels: labels,
datasets: [{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: tweet
}, {
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: tweet
}]
};
var ctx = document.getElementById("myChart").getContext("2d");
ctx.canvas.width = 1000;
ctx.canvas.height = 800;
var myChart = new Chart(ctx).Bar(data);
});
data.json:
[{
"timestamp": "Monday",
"original_tweet": "756",
"retweets": "345",
"shared": "34",
"quoted": "14"
}, {
"timestamp": "Tuesday",
"original_tweet": "456",
"retweets": "345",
"shared": "34",
"quoted": "14"
}, {
"timestamp": "Wednesday",
"original_tweet": "956",
"retweets": "345",
"shared": "34",
"quoted": "14"
}]
截圖: