gpt4 book ai didi

jquery - 来自 jquery ajax 的 d3js 饼图 - 关联图表上的 json 键和值

转载 作者:行者123 更新时间:2023-12-01 00:07:17 25 4
gpt4 key购买 nike

所以我有一个已经可以工作的 jquery ajax 应用程序,我正在尝试使用 d3js 创建图形。我对 jq 非常熟悉,但这是我使用 d3 的第一个项目。

所以,我的 html 文件使用 jquery.ajax 从 php 脚本/mysql 数据库请求 json 编码数据。我的所有数据都以类似于以下的格式返回:

{"status":"失败","msg":"请求错误。"}

或者如果是这样的数据(这是用户的年龄分割):

{"status":"找到","msg":{"under_18":103,"18-23":841,"24-29":1436,"30-36":1058, "37-46":907,"47-56":483,"over_56":200}}

我已经有了与 jq 一起使用的登录/ session /cookie 内容。我可以从我的 ajax api 请求数据,格式化它,并将其绘制到屏幕上,没有任何问题。

所以我尝试使用 d3js 创建一个带有我上面发布的第二个 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图表呈现“正常”,但在上面代码中的第 9 行我调用:

data = d3.values(result.msg),

提取 d3 的值以生成饼图。但饼图上的标签是我给它的值,但我想显示键。

例如“18岁以下”、“18-23岁”等等......

这可能吗?
在第 #31 行,我正在设置文本:

.text(function(d, i) { return d.value.toFixed(2); });

但在这种情况下“d”只是数值。我想我可以使用“i”来查找原始“result.msg”中的键,但由于键是字符串而不是整数(如数组),我不知道如何执行此操作。

好的,所以我解决了我的问题。请参阅下面我的回答,这是一个新问题,是否可以将标签移到饼图之外?还是滚动?

最佳答案

我明白了。

创建标签:

labels = d3.keys(result.msg)

然后在第 31 行:

.text(function(d, i) { return labels[i]; });

我花了一整天的时间破解了这段代码,当我把它发布到这里时,我就明白了。哈哈

关于jquery - 来自 jquery ajax 的 d3js 饼图 - 关联图表上的 json 键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13161454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com