如何使用 D3 和 JS 字典制作多个饼图

How to make multiple pie charts using D3 and a JS dictionary?

本文关键字:字典 何使用 D3 JS      更新时间:2023-09-26

我正在尝试改编Mike Bostock制作多个饼图示例中的代码。它非常简洁,但我正在努力理解代码的一个基本部分:

// Define the data as a two-dimensional array of numbers. If you had other
// data to associate with each number, replace each number with an object, e.g.,
// `{key: "value"}`.
var data = [
  [11975,  5871, 8916, 2868],
  [ 1951, 10048, 2060, 6171],
  [ 8010, 16145, 8090, 8045],
  [ 1013,   990,  940, 6907]
];

使这项工作{key: "value"}的例子是什么?我试过了

[{key1: 100}, {key2: 200}]

[{key1: 100, key2: 200}]

[{'key1': 100, 'key2': 200}] 以及其他一些排列。

我的目标是使用 json 对象而不是像这样的数据结构,但我想更好地了解如何构造正确的数据结构。

要生成图表(通过要点),使用以下代码:

var m = 10,
    r = 100,
    z = d3.scale.category20c();
var svg = d3.select(".sentiment-pie-chart-1").selectAll("svg")
    .data(data)
  .enter().append("svg:svg")
    .attr("width", (r + m) * 2)
    .attr("height", (r + m) * 2)
  .append("svg:g")
    .attr("transform", "translate(" + (r + m) + "," + (r + m) + ")");
svg.selectAll("path")
    .data(d3.layout.pie())
  .enter().append("svg:path")
    .attr("d", d3.svg.arc()
    .innerRadius(r / 2)
    .outerRadius(r))
    .style("fill", function(d, i) { return z(i); });

您可以使用任意结构(包括您列出的结构),只要您同时替换饼图布局从此结构中提取值的方式即可。这意味着您可能希望一致的键名称。例如,对于数据结构

[{key1: 100}, {key1: 200}]

您需要使用 .value() 函数按如下方式定义饼图布局——我认为这是您的问题。

svg.selectAll("path")
   .data(d3.layout.pie().value(function(d) { return d.key1; })
// etc

这将获取每个数组中的每个元素(请注意,这里有 2 个嵌套的对象数组),并获取成员.key1来计算饼图分数。

<html>
<head>
    <title>
        Pie chart
    </title>
<script type="text/javascript" src='d3.v3.min.js' charset='utf-8' ></script>
</head>
    <body>
        <script type="text/javascript">
            var data = [
                [11975,  5871, 8916, 2868],
                [ 1951, 10048, 2060, 6171],
                [ 8010, 16145, 8090, 8045],
                [ 1013,   990,  940, 6907]
            ];
            //For the data above you can convert each data row in array of object.
            //like,
            var newData = data[0].map(function(val){
                return {value : val} ;
            });
            //here you will get  : 
            // var newData = [
            //     {value : 11975} ,
            //     {value : 5871} ,
            //     {value : 8916} ,
            //     {value : 2868} ];
            // You can do same thing for each data row  .
            var width = 1100 , height = 650 , radius = 250 ,
            color = ["#C5AAF5","#FB7374","#A3CBF1","#79BFA1","#F5A352","#94B3C8", "#F9D08B","#B2AC4E","#64BD4F","#C09372"];
            var colorDescriptions = [];
            var svgContainer = d3.select("body") // create svg container
                .append("svg:svg")
                .data([newData])
                .attr("width", width)
                .attr("height", height)
                .append("svg:g")
                .attr("transform", "translate(" + 300 + "," + 300 + ")") ;;
            // Create new svg containier for each element && transform it to diff point.
            var arc = d3.svg.arc() // draw arc of given radius
                .outerRadius(radius);
            var pie = d3.layout.pie() // assign data for pie chart
                .value(function(d) { return d.value; });
            var arcs = svgContainer.selectAll("g.slice") // slice the circle
                .data(pie)   
                .enter()
                .append("svg:g")
                .attr("class", "slice");
            arcs.append("svg:path") // fill color in each slice
                .attr("fill", function(d, i) { return color[i]; } )
                .attr("d", arc)
            arcs.append("svg:text") // write slice information values
                .attr("transform", function(d) {
                d.innerRadius = 0;
                d.outerRadius = radius;
                    return "translate(" + arc.centroid(d) + ")";
                })
                .attr("text-anchor", "middle")
                .text(function(d, i) { return newData[i].value; })
                .style("font-family","monospace")
                .style("fill", "#3f3f3f")
                .style("font-size", "20px");
            var description = svgContainer.append("g").attr("class", "description"); // pie chart description
            var desc_label = description.append("text")
                .attr("class", "description")
                .attr("y", 300)
                .attr("x", 000)
                .text("Pie Chart")
                .style("font-weight", "bold")
                .style("font-size", "20px")
                .style("text-anchor", "middle"); 
        </script>
    </body>
</html>