所以我有一個已經工作的jquery ajax應用程序,我試圖創建使用d3js圖。我對jq非常熟悉,但這是我第一個使用d3的項目。從jquery ajax d3js餅圖 - 關聯json鍵和圖表上的值
因此,我的html文件使用jquery.ajax從php腳本/ mysql數據庫請求json編碼的數據。我的所有數據返回的格式與此類似:
{"status":"Failed","msg":"Bad request."}
,或者如果它的數據是這樣的(這是用戶的年齡細分):
{"status":"Found","msg":{"under_18":103,"18-23":841,"24-29":1436,"30-36":1058,"37-46":907,"47-56":483,"over_56":200}}
我已經有登錄/ session/cookie與jq一起工作。我可以從我的ajax api請求數據,格式化它,並將它繪製到屏幕上,沒有任何問題。
所以即時通訊嘗試使用d3js創建一個餅圖w /第二json blob我張貼上面。這裏是一個代碼剪斷我的工作:
function ageDemographics() {
closure(
'action=ageDemographics',
function(result) {
var width = 200,
height = 200,
outerRadius = Math.min(width, height)/2,
innerRadius = outerRadius * .6,
data = d3.values(result.msg),
color = d3.scale.category20(),
donut = d3.layout.pie(),
arc = d3.svg.arc().innerRadius(0).outerRadius(outerRadius);
var vis = d3.select("#ageDemographics")
.append("svg")
.data([data])
.attr("width", width)
.attr("height", height);
var arcs = vis.selectAll("g.arc")
.data(donut)
.enter().append("g")
.attr("class", "arc")
.attr("transform", "translate(" + outerRadius + "," + outerRadius + ")");
arcs.append("path")
.attr("fill", function(d, i) { return color(i); })
.attr("d", arc);
arcs.append("text")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.attr("display", function(d) { return d.value > .15 ? null : "none"; })
.text(function(d, i) { return d.value.toFixed(2); });
},
function(xhr, status, thrown) {
setupLoginForm();
$('#error').html('You have been logged out.<br class="clear"/><br/>');
}
);
}
function closure(data, success, error) {
$.ajax({
type: "POST",
url: 'http://localhost/analytics/api/ajax.php',
data: data,
cache: false,
success: success,
error: error
});
}
我使用的pie example from the d3js git repo和圖表呈現「OK」,但在上面的代碼行#9我打電話:
data = d3.values(result.msg),
拉出d3的值以生成餅圖。但餡餅上的標籤是我給它的值,但我想要顯示的是鍵。
例如「18歲以下」,「18-23歲」等等...
這是可能的嗎?
上線#31我設置與文本:
.text(function(d, i) { return d.value.toFixed(2); });
但在這種情況下,「d」只是數值。我想我可以使用「我」來查找原來的「result.msg」中的鍵,但由於鍵是字符串不是整數(如數組),我不知道如何做到這一點。
好吧,所以我解決了我的問題。看到我的答案在下面,這裏有一個新的問題, 是否有可能將標籤移出餡餅?或翻車?
我很感興趣,因爲我想做類似的事情,但更復雜,我是初學D3js。你能告訴我一些例子如何動態(通過AJAX)改變D3js可視化?使用setInterval函數。 – Kamil
@kamylko我通過jquery ajax調用我的ajax,然後將生成的JSON blob傳遞給d3函數。我在考試中刪除了那部分內容,因爲它與我的問題沒有直接關係。 – xero