gpt4 book ai didi

javascript - 使用存储在 d3.js 数组中的数据绘制 d3.svg.arc 元素

转载 作者:行者123 更新时间:2023-11-30 10:34:18 25 4
gpt4 key购买 nike

嗨,我正在尝试多次绘制 coxcomb charts .该代码绘制了一个这样的图表。 jsfiddle example

我遇到的问题:如何排序我的数据,以便绘制多个这样的图表?

//data
var data = [
{"label": "January", "value": 150, "time": 1},
{"label": "February", "value": 65, "time": 2},
{"label": "March", "value": 50, "time": 3},
{"label": "April", "value": 75, "time": 4},
{"label": "May", "value": 150, "time": 5},
{"label": "June", "value": 65, "time": 6}
];

//container
var svg = d3.select("body")
.append("svg:svg")
.attr("width", 1000)
.attr("height", 1000);

var pi = Math.PI;

var arc = d3.svg.arc()
.innerRadius(0)
.outerRadius(function(d,i) {return (0 + d.value); })
.startAngle(function(d,i) { return ((d.time - 1) * 60 * pi / 180); })
.endAngle(function(d) { return (d.time * 60 * pi / 180 ); });

var chartContainer = svg.append("g")
.attr('class', 'some_class')
.attr("transform", "translate(450, 300)");

chartContainer.selectAll("path")
.data(data)
.enter()
.append("path")
.attr("d", arc)
.attr("class", "arc");

我想也许我可以按以下方式订购数据:

var data2 = [
{label: "Rose.chart1", value: [150,65,50,75,150,65]}
{label: "Rose.chart2", value: [130,50,30,10,50,70]}
]

但这意味着我将不得不重写以下内容:

1.) 定义弧变量

var arc = d3.svg.arc()
.innerRadius(0)
.outerRadius(function(d,i) {return (0 + d.value); })
.startAngle(function(d,i) { return ((d.time - 1) * 60 * pi / 180); })
.endAngle(function(d) { return (d.time * 60 * pi / 180 ); });

2.) 将数据绑定(bind)到选择

chartContainer.selectAll("path")
.data(data)
.enter()
.append("path")
.attr("d", arc)
.attr("class", "arc");

我想我可能需要输入数据对象 (data2),然后再输入值元素。请原谅我的描述。

function(d.value) {???}

最佳答案

首先嵌套数据,作为数组的数组。所以你将拥有:

//data
var data = [
[
{"label": "January", "value": 150, "time": 1},
{"label": "February", "value": 65, "time": 2},
{"label": "March", "value": 50, "time": 3},
{"label": "April", "value": 75, "time": 4},
{"label": "May", "value": 150, "time": 5},
{"label": "June", "value": 65, "time": 6}
],
[
{"label": "January", "value": 123, "time": 1},
{"label": "February", "value": 62345, "time": 2},
{"label": "March", "value": 5340, "time": 3},
{"label": "April", "value": 72315, "time": 4},
{"label": "May", "value": 11350, "time": 5},
{"label": "June", "value": 6135, "time": 6}
],
];

然后将图表嵌套在绑定(bind)到数据的父容器中:

svg.selectAll(".charts")
.data(data)
.enter()
.append("g")
// Translate each chart based on 'i'
.attr("transform", function(d, i) { return "translate(" + ((i+1) * 450) + ", 300)");
.each(function(chartData, i) {
var chartContainer = d3.select(this);// Selects the containing 'g'
// The rest is what you already wrote
chartContainer.selectAll("path")
.data(data)
.enter()
.append("path")
.attr("d", arc)
.attr("class", "arc");
});

关于javascript - 使用存储在 d3.js 数组中的数据绘制 d3.svg.arc 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14950233/

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