使用D3僅
d3.json(url, function (error, result) {
var data = [];
for (i = 0; i < result.feed.entry.length; i += 1) {
data.push({
"animal": result.feed.entry[i].gsx$animal.$t,
"population": result.feed.entry[i].gsx$population.$t
});
}
pie_chart(data, "#chart1");
});
使用jQuery
$.get(url, function (result) {
var data = [];
$(result.feed.entry).each(function() {
data.push({"animal": this.gsx$animal.$t, "population": this.gsx$population.$t});
});
pie_chart(data, "#chart2");
});
使用tabletop。
Tabletop.init({
key: key,
callback: function (data, tabletop) {
pie_chart(data, "#chart3");
},
simpleSheet: true
});
以下僅僅是一個簡單的例子,從谷歌電子表格中獲取數據,並把它變成一個D3 pie chart。
//draws a pie chart with D3
function pie_chart(data, id) {
var w = 400;
var h = 400;
var r = h/2;
var color = d3.scale.category20c();
var vis = d3.select(id).append("svg:svg").data([data]).attr("width", w).attr("height", h).append("svg:g").attr("transform", "translate(" + r + "," + r + ")");
var pie = d3.layout.pie().value(function (d) {
return d.population;
});
var arc = d3.svg.arc().outerRadius(r);
var arcs = vis.selectAll("g.slice").data(pie).enter().append("svg:g").attr("class", "slice");
arcs.append("svg:path")
.attr("fill", function (d, i) {
return color(i);
})
.attr("d", function (d) {
return arc(d);
});
arcs.append("svg:text").attr("transform", function (d) {
d.innerRadius = 0;
d.outerRadius = r;
return "translate(" + arc.centroid(d) + ")";
}).attr("text-anchor", "middle").text(function (d, i) {
return data[i].animal;
});
}
//the key of google spreadsheet
var key = "1moczdbrfFwCp0L4Ube1a4GevuDcj2XQmCnpjArF_UEY";
//the url for jQuery and D3
var url = "https://spreadsheets.google.com/feeds/list/" + key + "/od6/public/values?alt=json";
var i = 0;
//D3 only
d3.json(url, function (error, result) {
var data = [];
for (i = 0; i < result.feed.entry.length; i += 1) {
data.push({
"animal": result.feed.entry[i].gsx$animal.$t,
"population": result.feed.entry[i].gsx$population.$t
});
}
pie_chart(data, "#chart1");
});
//Jquery
$.get(url, function (result) {
var data = [];
$(result.feed.entry).each(function() {
data.push({"animal": this.gsx$animal.$t, "population": this.gsx$population.$t});
});
pie_chart(data, "#chart2");
});
//tabletop
Tabletop.init({
key: key,
callback: function (data, tabletop) {
pie_chart(data, "#chart3");
},
simpleSheet: true
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tabletop.js/1.4.3/tabletop.js"></script>
<div id="chart1" style="width: 480px; height: 400px;"><span>D3 only</span></div>
<hr>
<div id="chart2" style="width: 480px; height: 400px;"><span>Jquery</span></div>
<hr>
<div id="chart3" style="width: 480px; height: 400px;"><span>Tabletop</span></div>
請不要使用從人的電子郵件未經他們同意你的樣本數據。 –
Oups。讓我們快速消除它! – Hugolpz
@MaximilianPeters:非常感謝。我一直在這個代碼上寫了很多,所以我忘記了我的表格上有電子郵件。 – Hugolpz