D3.js堆积条形图layout.stack()

时间:2018-05-23 13:56:32

标签: javascript d3.js

我在D3中是全新的,我试图在this gist的帮助下创建条形图,但我的数据与gist中的数据不同。我的数据看起来像这样

[
    {"identifier":"HD 143761 b","period":"39.8458","method":"RV","year":"2016","status":"Confirmed planets"},
    {"identifier":"HD 143761 c","period":"102.54","method":"RV","year":"2016","status":"Confirmed planets"},
    {"identifier":"KOI-1843.03","period":"0.1768913","method":"transit","year":"2012","status":"Controversial"},
    {"identifier":"HD 143761 b","period":"39.8458","method":"RV","year":"2016","status":"Confirmed planets"},
    {"identifier":"HD 143761 c","period":"102.54","method":"RV","year":"2016","status":"Confirmed planets"},
    {"identifier":"KOI-1843.03","period":"0.1768913","method":"transit","year":"2012","status":"Controversial"},
    {"identifier":"GJ 160.2 b","period":"5.2354","method":"RV","year":"2014","status":"Controversial"},
    {"identifier":"Kepler-566 b","period":"18.427946240","method":"transit","year":"2016","status":"Confirmed planets"}
]

我不了解如何为我的目的生成数据集。我试图控制.log数据集var并以手动方式重新创建,但它不起作用。

i want the x axis to have different methods and years to be stacked.

这是我试图做的,但没有用。

var figOne = [];
for (var i = 0; i < data.length; i++) {
if(data[i]['method'] in figOne)
  {
    if('"' + data[i]['year'] + '"' in figOne[data[i]['method']])
    {
      figOne[data[i]['method']]['"' + data[i]['year'] + '"'] += 1;
    }
    else
    {
      figOne[data[i]['method']]['"' + data[i]['year'] + '"'] = 1;        
    }
  }
  else
  {
    figOne[data[i]['method']] = [];
    figOne[data[i]['method']]['"' + data[i]['year'] + '"'] = 1;
  }
}

这是它输出到控制台的内容:

console log

修改

这是我的最新代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>d3.js learning</title>
    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
    <style type="text/css">
        svg {
            font: 10px sans-serif;
            shape-rendering: crispEdges;
        }
        .axis path,
        .axis line {
            fill: none;
            stroke: #000;
        }

        path.domain {
            stroke: none;
        }

        .y .tick line {
            stroke: #ddd;
        }
    </style>
</head>
<body>
    <script type="text/javascript">

        // Setup svg using Bostock's margin convention

        var margin = { top: 20, right: 160, bottom: 35, left: 30 };

        var width = 960 - margin.left - margin.right,
            height = 500 - margin.top - margin.bottom;

        var svg = d3.select("body")
            .append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
            .append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");


        /* Data in strings like it would be if imported from a csv */

        var data = [{
            "identifier": "HD 143761 b",
            "period": "39.8458",
            "method": "RV",
            "year": "2016",
            "status": "Confirmed planets"
        },
        {
            "identifier": "HD 143761 c",
            "period": "102.54",
            "method": "RV",
            "year": "2016",
            "status": "Confirmed planets"
        },
        {
            "identifier": "KOI-1843.03",
            "period": "0.1768913",
            "method": "transit",
            "year": "2012",
            "status": "Controversial"
        },
        {
            "identifier": "HD 143761 b",
            "period": "39.8458",
            "method": "RV",
            "year": "2016",
            "status": "Confirmed planets"
        },
        {
            "identifier": "HD 143761 c",
            "period": "102.54",
            "method": "RV",
            "year": "2016",
            "status": "Confirmed planets"
        },
        {
            "identifier": "KOI-1843.03",
            "period": "0.1768913",
            "method": "transit",
            "year": "2012",
            "status": "Controversial"
        },
        {
            "identifier": "GJ 160.2 b",
            "period": "5.2354",
            "method": "RV",
            "year": "2014",
            "status": "Controversial"
        },
        {
            "identifier": "Kepler-566 b",
            "period": "18.427946240",
            "method": "transit",
            "year": "2016",
            "status": "Confirmed planets"
        }
        ];

        var newData1 = []

        var keys = Array.from(new Set(data.map(function (d) {
            return d.method;
        })));

        var years = Array.from(new Set(data.map(function (d) {
            return d.year;
        })));

        for (i in keys) {
            val = {}
            val['method'] = keys[i]
            for (j in data) {
                if (data[j]['method'] == keys[i]) {
                    for (k2 in years) {
                        if (years[k2] == data[j]['year']) {
                            if (val.hasOwnProperty(data[j]['year'])) {
                                val[data[j]['year']] += 1
                            } else {
                                val[data[j]['year']] = 0
                            }
                        }
                    }
                }
            }
            newData1.push(val)
        }
        console.log(JSON.stringify(newData1))
        /*
        var newData2 = []
        for (i in keys) {
        val = {}
        val['method'] = keys[i]
        for (k in years) {
            val[years[k]] = 0
        }
        for (j in data) {
            if (data[j]['method'] == keys[i]) {
            for (k2 in years) {
                if (years[k2] == data[j]['year']) {
                val[data[j]['year']] += 1
                }
            }
            }
        }
        newData2.push(val)
        }
        console.log(JSON.stringify(newData2))
        */
        var parse = d3.time.format("%Y").parse;


        // Transpose the data into layers
        var dataset = d3.layout.stack()(["RV", "transit", "microlensing"].map(function (method) {
            return newData1.map(function (d) {
                return { x: parse(d.year), y: +d[method] };
            });
        }));


        // Set x, y and colors
        var x = d3.scale.ordinal()
            .domain(dataset[0].map(function (d) { return d.x; }))
            .rangeRoundBands([10, width - 10], 0.02);

        var y = d3.scale.linear()
            .domain([0, d3.max(dataset, function (d) { return d3.max(d, function (d) { return d.y0 + d.y; }); })])
            .range([height, 0]);

        var colors = ["b33040", "#d25c4d", "#f2b447"];


        // Define and draw axes
        var yAxis = d3.svg.axis()
            .scale(y)
            .orient("left")
            .ticks(5)
            .tickSize(-width, 0, 0)
            .tickFormat(function (d) { return d });

        var xAxis = d3.svg.axis()
            .scale(x)
            .orient("bottom")
            .tickFormat(d3.time.format("%Y"));

        svg.append("g")
            .attr("class", "y axis")
            .call(yAxis);

        svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis);


        // Create groups for each series, rects for each segment 
        var groups = svg.selectAll("g.cost")
            .data(dataset)
            .enter().append("g")
            .attr("class", "cost")
            .style("fill", function (d, i) { return colors[i]; });

        var rect = groups.selectAll("rect")
            .data(function (d) { return d; })
            .enter()
            .append("rect")
            .attr("x", function (d) { return x(d.x); })
            .attr("y", function (d) { return y(d.y0 + d.y); })
            .attr("height", function (d) { return y(d.y0) - y(d.y0 + d.y); })
            .attr("width", x.rangeBand())
            .on("mouseover", function () { tooltip.style("display", null); })
            .on("mouseout", function () { tooltip.style("display", "none"); })
            .on("mousemove", function (d) {
                var xPosition = d3.mouse(this)[0] - 15;
                var yPosition = d3.mouse(this)[1] - 25;
                tooltip.attr("transform", "translate(" + xPosition + "," + yPosition + ")");
                tooltip.select("text").text(d.y);
            });


        // Draw legend
        var legend = svg.selectAll(".legend")
            .data(colors)
            .enter().append("g")
            .attr("class", "legend")
            .attr("transform", function (d, i) { return "translate(30," + i * 19 + ")"; });

        legend.append("rect")
            .attr("x", width - 18)
            .attr("width", 18)
            .attr("height", 18)
            .style("fill", function (d, i) { return colors.slice().reverse()[i]; });

        legend.append("text")
            .attr("x", width + 5)
            .attr("y", 9)
            .attr("dy", ".35em")
            .style("text-anchor", "start")
            .text(function (d, i) {
                switch (i) {
                    case 0: return "RV";
                    case 1: return "Transit";
                    case 2: return "Microlensing";
                }
            });


        // Prep the tooltip bits, initial display is hidden
        var tooltip = svg.append("g")
            .attr("class", "tooltip")
            .style("display", "none");

        tooltip.append("rect")
            .attr("width", 30)
            .attr("height", 20)
            .attr("fill", "white")
            .style("opacity", 0.5);

        tooltip.append("text")
            .attr("x", 15)
            .attr("dy", "1.2em")
            .style("text-anchor", "middle")
            .attr("font-size", "12px")
            .attr("font-weight", "bold");

    </script>
</body>

</html>

1 个答案:

答案 0 :(得分:0)

如果我理解正确,你需要为每种方法和每年计算方法。

您的数据应如下所示:

[{"year":"2016","RV":4,"transit":1},
 {"year":"2012","RV":0,"transit":2},
 {"year":"2014","RV":1,"transit":0}]

请看下面的小提琴:

var data = [{
    "identifier": "HD 143761 b",
    "period": "39.8458",
    "method": "RV",
    "year": "2016",
    "status": "Confirmed planets"
  },
  {
    "identifier": "HD 143761 c",
    "period": "102.54",
    "method": "RV",
    "year": "2016",
    "status": "Confirmed planets"
  },
  {
    "identifier": "KOI-1843.03",
    "period": "0.1768913",
    "method": "transit",
    "year": "2012",
    "status": "Controversial"
  },
  {
    "identifier": "HD 143761 b",
    "period": "39.8458",
    "method": "RV",
    "year": "2016",
    "status": "Confirmed planets"
  },
  {
    "identifier": "HD 143761 c",
    "period": "102.54",
    "method": "RV",
    "year": "2016",
    "status": "Confirmed planets"
  },
  {
    "identifier": "KOI-1843.03",
    "period": "0.1768913",
    "method": "transit",
    "year": "2012",
    "status": "Controversial"
  },
  {
    "identifier": "GJ 160.2 b",
    "period": "5.2354",
    "method": "RV",
    "year": "2014",
    "status": "Controversial"
  },
  {
    "identifier": "Kepler-566 b",
    "period": "18.427946240",
    "method": "transit",
    "year": "2016",
    "status": "Confirmed planets"
  }
]

var keys = Array.from(new Set(data.map(function(d) {
  return d.method;
})));

var years = Array.from(new Set(data.map(function(d) {
  return d.year;
})));


var newData2 = []
for (i in years) {
  val = {}
  val['year'] = years[i]
  for (k in keys) {
    val[keys[k]] = 0
  }
  for (j in data) {
    if (data[j]['year'] == years[i]) {
      for (k2 in keys) {
        if (keys[k2] == data[j]['method']) {
          val[data[j]['method']] += 1
        }
      }
    }
  }
  newData2.push(val)
}
console.log(JSON.stringify(newData2))

以下是您分享的代码的摘要:

// Setup svg using Bostock's margin convention

var margin = {
  top: 20,
  right: 160,
  bottom: 50,
  left: 30
};

var width = 960 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom;

var svg = d3.select("body")
  .append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");


/* Data in strings like it would be if imported from a csv */

var data = [{
    "identifier": "HD 143761 b",
    "period": "39.8458",
    "method": "RV",
    "year": "2016",
    "status": "Confirmed planets"
  },
  {
    "identifier": "HD 143761 c",
    "period": "102.54",
    "method": "RV",
    "year": "2016",
    "status": "Confirmed planets"
  },
  {
    "identifier": "KOI-1843.03",
    "period": "0.1768913",
    "method": "transit",
    "year": "2012",
    "status": "Controversial"
  },
  {
    "identifier": "HD 143761 b",
    "period": "39.8458",
    "method": "RV",
    "year": "2016",
    "status": "Confirmed planets"
  },
  {
    "identifier": "HD 143761 c",
    "period": "102.54",
    "method": "RV",
    "year": "2016",
    "status": "Confirmed planets"
  },
  {
    "identifier": "KOI-1843.03",
    "period": "0.1768913",
    "method": "transit",
    "year": "2012",
    "status": "Controversial"
  },
  {
    "identifier": "GJ 160.2 b",
    "period": "5.2354",
    "method": "RV",
    "year": "2014",
    "status": "Controversial"
  },
  {
    "identifier": "Kepler-566 b",
    "period": "18.427946240",
    "method": "transit",
    "year": "2016",
    "status": "Confirmed planets"
  },

  {
    "identifier": "Kepler-566 b", //Dummy data added
    "period": "18.427946240",
    "method": "microlensing",
    "year": "2012",
    "status": "Confirmed planets"
  },
  {
    "identifier": "Kepler-566 b",
    "period": "18.427946240",
    "method": "microlensing",
    "year": "2014",
    "status": "Confirmed planets"
  }
];



var keys = Array.from(new Set(data.map(function(d) {
  return d.method;
})));

var years = Array.from(new Set(data.map(function(d) {
  return d.year;
})));

/*
var newData1 = []
for (i in keys) {
  val = {}
  val['method'] = keys[i]
  for (j in data) {
    if (data[j]['method'] == keys[i]) {
      for (k2 in years) {
        if (years[k2] == data[j]['year']) {
          if (val.hasOwnProperty(data[j]['year'])) {
            val[data[j]['year']] += 1
          } else {
            val[data[j]['year']] = 0
          }
        }
      }
    }
  }
  newData1.push(val)
}
console.log(JSON.stringify(newData1))*/

var newData1 = []
for (i in years) {
  val = {}
  val['year'] = years[i]
  for (k in keys) {
    val[keys[k]] = 0
  }
  for (j in data) {
    if (data[j]['year'] == years[i]) {
      for (k2 in keys) {
        if (keys[k2] == data[j]['method']) {
          val[data[j]['method']] += 1
        }
      }
    }
  }
  newData1.push(val)
}

newData1.sort(function(x, y) {
  return d3.ascending(x.year, y.year);
})

console.log(JSON.stringify(newData1))
var parse = d3.time.format("%Y").parse;


// Transpose the data into layers
var dataset = d3.layout.stack()(["RV", "transit", "microlensing"].map(function(method) {
  return newData1.map(function(d) {
    return {
      x: parse(d.year),
      y: +d[method]
    };
  });
}));



// Set x, y and colors
var x = d3.scale.ordinal()
  .domain(dataset[0].map(function(d) {
    return d.x;
  }))
  .rangeRoundBands([10, width - 10], 0.02);

var y = d3.scale.linear()
  .domain([0, d3.max(dataset, function(d) {
    return d3.max(d, function(d) {
      return d.y0 + d.y;
    });
  })])
  .range([height, 0]);

var colors = ["b33040", "#d25c4d", "#f2b447"];


// Define and draw axes
var yAxis = d3.svg.axis()
  .scale(y)
  .orient("left")
  .ticks(5)
  .tickSize(-width, 0, 0)
  .tickFormat(function(d) {
    return d
  });

var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom")
  .tickFormat(d3.time.format("%Y"));

svg.append("g")
  .attr("class", "y axis")
  .call(yAxis);

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);


// Create groups for each series, rects for each segment 
var groups = svg.selectAll("g.cost")
  .data(dataset)
  .enter().append("g")
  .attr("class", "cost")
  .style("fill", function(d, i) {
    return colors[i];
  });

var rect = groups.selectAll("rect")
  .data(function(d) {
    return d;
  })
  .enter()
  .append("rect")
  .attr("x", function(d) {
    return x(d.x);
  })
  .attr("y", function(d) {
    return y(d.y0 + d.y);
  })
  .attr("height", function(d) {
    return y(d.y0) - y(d.y0 + d.y);
  })
  .attr("width", x.rangeBand())
  .on("mouseover", function() {
    tooltip.style("display", null);
  })
  .on("mouseout", function() {
    tooltip.style("display", "none");
  })
  .on("mousemove", function(d) {
    var xPosition = d3.mouse(this)[0] - 15;
    var yPosition = d3.mouse(this)[1] - 25;
    tooltip.attr("transform", "translate(" + xPosition + "," + yPosition + ")");
    tooltip.select("text").text(d.y);
  });


// Draw legend
var legend = svg.selectAll(".legend")
  .data(colors)
  .enter().append("g")
  .attr("class", "legend")
  .attr("transform", function(d, i) {
    return "translate(30," + i * 19 + ")";
  });

legend.append("rect")
  .attr("x", width - 18)
  .attr("width", 18)
  .attr("height", 18)
  .style("fill", function(d, i) {
    return colors.slice()[i];
  });

legend.append("text")
  .attr("x", width + 5)
  .attr("y", 9)
  .attr("dy", ".35em")
  .style("text-anchor", "start")
  .text(function(d, i) {
    switch (i) {
      case 0:
        return "RV";
      case 1:
        return "Transit";
      case 2:
        return "Microlensing";
    }
  });


// Prep the tooltip bits, initial display is hidden
var tooltip = svg.append("g")
  .attr("class", "tooltip")
  .style("display", "none");

tooltip.append("rect")
  .attr("width", 30)
  .attr("height", 20)
  .attr("fill", "white")
  .style("opacity", 0.5);

tooltip.append("text")
  .attr("x", 15)
  .attr("dy", "1.2em")
  .style("text-anchor", "middle")
  .attr("font-size", "12px")
  .attr("font-weight", "bold");
svg {
  font: 10px sans-serif;
  shape-rendering: crispEdges;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
}

path.domain {
  stroke: none;
}

.y .tick line {
  stroke: #ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.3.13/d3.min.js"></script>