带有D3的堆积条形图

时间:2014-06-24 14:04:18

标签: javascript d3.js

我想用d3创建堆积条形图。 我在CSV文件中有这些数据:

Type Sum Color Regular 29756.85897 green Regular 9756.85897 blue

我希望每行在Y轴上显示在另一行之上。 What I get now

例如在这张照片中,蓝色区域应该从y = 9756开始,直到y = 39512.

我应该改变什么?

这是相关的HTML代码:


整个代码:

<!DOCTYPE html>

<html>
<head>
<meta charset="utf-8">
<style>

body {
  font: 10px sans-serif;
 margin:auto;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.bar1 {
  fill: #00FF66;

}

.bar1:hover {
  fill: black ;
}

.x.axis path {
  display: none;
}

.d3-tip {
  line-height: 1;
  font-weight: bold;
  padding: 12px;
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  border-radius: 2px;
}

/* Creates a small triangle extender for the tooltip */
.d3-tip:after {
  box-sizing: border-box;
  display: inline;
  font-size: 10px;
  width: 100%;
  line-height: 1;
  color: rgba(0, 0, 0, 0.8);
  content: "\25BC";
  position: absolute;
  text-align: center;
}

/* Style northward tooltips differently */
.d3-tip.n:after {
  margin: -1px 0 0 0;
  top: 100%;
  left: 0;
}
</style>
<body>

<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"></script>
<script>

var margin = {top: 80, right: 90, bottom: 30, left: 90},
    width = 1000 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var formatPercent = d3.format(".0%");
//יצירת X
//יאכלס את סוגי הרכב השונים
var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);
//יצירת ציר y
//יציג בר עבור מחיר הרכב המוצע לדילרים
var y = d3.scale.linear()
    .range([height, 0]);


var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

//יצירת ציר הY
//והצמדתו לצד שמאל
var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left").ticks(4)

var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    return "<strong></strong>"+d.Type+"<br><strong></strong> <span style='color:#00FF66'>" + d.Sum + "</span>";
  })




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 + ")");

svg.call(tip);
//קליטת הטבלה והגדרת הטווחים על הצירים
d3.csv("Targil2.csv", type, function(error, data) {
  x.domain(data.map(function(d) { return d.Type; }));
  y.domain([0, d3.max(data, function(d) { return d.Sum*2; })]);

  var stack = d3.layout.stack();
  .x(function(d) { return d.Type }) // tell d3 to use Type as x value
  .y(function(d) { return d.Sum }); // tell d3 to use Sum as y value
   var stackData = stack(data);

 //הוספה של 2 הצירים
  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
  .attr("class", "y axis axisLeft")
  .attr("transform", "translate(0,0)")
  .call(yAxis)
.append("text")
  .attr("y", 6)
  .attr("dy", "-2em")
  .style("text-anchor", "end")
  .style("text-anchor", "end")
  .text("Price");


//הוספת בר הנתונים
  svg.selectAll(".bar")
      .data(data)
    .enter().append("rect")

      .attr("x", function(d) { return x(d.Type); })
      .attr("width", x.rangeBand())
      .attr("y", function(d) { return d.y0 })
      .attr("height", function(d) { return (height - y(d.Sum)); })

      .style("fill", function(d){
         if(d["Color"] == "green"){  return "green";}

         else return "#0066FF";})

      .on('mouseover', tip.show)
      .on('mouseout', tip.hide)

});

function type(d) {
  d.Sum = +d.Sum;

  return d;
}

</script>
</body>
</html>

我尝试使用你告诉我的那个堆栈功能,并改变了&#34; y&#34;的属性。 ,但它现在对我不起作用。我想我做错了什么。

2 个答案:

答案 0 :(得分:1)

首先,我想当你说

  

例如在这张照片中,蓝色区域应该从y = 9756开始直到   Y = 39512

你的意思是

  例如,在这张照片中,蓝色区域应该从y = 29756 开始,直到   Y = 39512

您所在的绿色区域是从029756,然后是从09756的蓝色区域。您需要将每个区域移到前一个区域的顶部。 最简单的方法是对数据进行预处理。 D3.js可以为您完成,请参阅Stack Layout。这会计算所有图层的y0y

修改

var stack = d3.layout.stack()
    .x(function(d) { return d.Type }) // tell d3 to use Type as x value
    .y(function(d) { return d.Sum }); // tell d3 to use Sum as y value
var stackData = stack(data);

之后,您的数据会得到增强,即每个条目都包含一个额外的yy0值,您可以直接使用这些值进行绘制(在yheight中属性)。

答案 1 :(得分:1)

你走了。

<!DOCTYPE html>

<html>
<head>
<meta charset="utf-8">
<style>

body {
  font: 10px sans-serif;
 margin:auto;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.bar1 {
  fill: #00FF66;

}

.bar1:hover {
  fill: black ;
}

.x.axis path {
  display: none;
}

.d3-tip {
  line-height: 1;
  font-weight: bold;
  padding: 12px;
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  border-radius: 2px;
}

/* Creates a small triangle extender for the tooltip */
.d3-tip:after {
  box-sizing: border-box;
  display: inline;
  font-size: 10px;
  width: 100%;
  line-height: 1;
  color: rgba(0, 0, 0, 0.8);
  content: "\25BC";
  position: absolute;
  text-align: center;
}

/* Style northward tooltips differently */
.d3-tip.n:after {
  margin: -1px 0 0 0;
  top: 100%;
  left: 0;
}
</style>
<body>

<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"></script>
<script>

var margin = {top: 80, right: 90, bottom: 30, left: 90},
    width = 1000 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var formatPercent = d3.format(".0%");
//יצירת X
//יאכלס את סוגי הרכב השונים
var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);
//יצירת ציר y
//יציג בר עבור מחיר הרכב המוצע לדילרים
var y = d3.scale.linear()
    .range([height, 0]);


var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

//יצירת ציר הY
//והצמדתו לצד שמאל
var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left").ticks(4)

var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    return "<strong></strong>"+d.Type+"<br><strong></strong> <span style='color:#00FF66'>" + d.Sum + "</span>";
  })




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 + ")");

svg.call(tip);
//קליטת הטבלה והגדרת הטווחים על הצירים
d3.csv("Targil2.csv", type, function(error, data) {
  window.dataSet = data;
  data.sort(function(x,y){
    var a = x.Sum; 
    var b = y.Sum; 
    return a > b ? -1 : a < b ? 1 : 0
  })
  x.domain(data.map(function(d) { return d.Type; }));
  y.domain([0, d3.max(data, function(d) { return d.Sum*2; })]);


  var stack = d3.layout.stack()
  .x(function(d) { return d.Type }) // tell d3 to use Type as x value
  .y(function(d) { return d.Sum }); // tell d3 to use Sum as y value
  // var stackData = stack(data);

 //הוספה של 2 הצירים
  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
  .attr("class", "y axis axisLeft")
  .attr("transform", "translate(0,0)")
  .call(yAxis)
.append("text")
  .attr("y", 6)
  .attr("dy", "-2em")
  .style("text-anchor", "end")
  .style("text-anchor", "end")
  .text("Price");



  var stackSoFar = 0;

//הוספת בר הנתונים
  svg.selectAll(".bar")
      .data(data)
    .enter().append("rect")
      .attr("x", function(d) { return x(d.Type); })
      .attr("width", x.rangeBand())
      .attr("y", function(d){
        d3.select(this)
          .attr("height", function(d2){
            var thisHeight = height - y(d.Sum);
            stackSoFar += thisHeight
            return thisHeight
          });
        return (height - stackSoFar)
      })
      .style("fill", function(d){
         if(d["Color"] == "green"){  return "green";}

         else return "#0066FF";})

      .on('mouseover', tip.show)
      .on('mouseout', tip.hide)

});

function type(d) {
  d.Sum = +d.Sum;

  return d;
}

</script>
</body>
</html>