Stacked Bar Chart D3js

Augusto

I'm trying to develop a stacked bar chart with d3js. But I'm having trouble with the position on the x-axis in the size of the bars... can someone help? Above it's my code and some data used... if necessary I change the way the data is coming... Thank's!

var dadosAcessos = [{
  _id: {
    fullname: 'Vis. Curso 13',
    recurso_id: 149,
    day: 17,
    month: 07,
    year: 2014,
    fulldata: '2014/07/17'
  },
  acessos: 7
}, {
  _id: {
    fullname: 'Vis. Curso 13',
    recurso_id: 149,
    day: 18,
    month: 07,
    year: 2014,
    fulldata: '2014/07/18'
  },
  acessos: 3
}, {
  _id: {
    fullname: 'Recurso',
    recurso_id: 150,
    day: 18,
    month: 07,
    year: 2014,
    fulldata: '2014/07/18'
  },
  acessos: 1
}, {
  _id: {
    fullname: 'Vis. Curso 13',
    recurso_id: 149,
    day: 14,
    month: 11,
    year: 2014,
    fulldata: '2014/11/14'
  },
  acessos: 1
}];

var color = d3.scale.category20();


// Chart dimensions
var margin = {
    top: 20,
    right: 80,
    bottom: 100,
    left: 40
  },
  width = 1000 - margin.right - margin.left,
  height = 300 - margin.top - margin.bottom;

// Define main svg element in #graph
var svg = d3.select("#acessos").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom);

var graph = svg.append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var y = d3.scale.linear().range([height, 0]);

var yAxis = d3.svg.axis()
  .scale(y)
  .orient("left");

var len = 0;

dadosAcessos.forEach(function(d) {
  d.fullname = d._id.fullname
  d.date = new Date(d._id.year + "/" + d._id.month + "/" + d._id.day);
  len++;
});

var nestByDate = d3.nest()
  .key(function(d) {
    return d.date;
  })
  .sortValues(function(a, b) {
    return ((a.acessos < b.acessos) ? -1 : 1);
    return 0;
  })
  .entries(dadosAcessos);

nestByDate.forEach(function(d) {
  var y0 = 0;
  var y1 = 0;
  d.vis = "1";
  d.values.forEach(function(d) {

    // y0 is the y axis start of the bar
    d.y0 = y0 + y1;

    // y1 is the y axis end of the bar
    d.y1 = y1 = d.acessos;

    // d.vis controls whether bars are visible or not
    d.vis = "1";
  });
});

var x = d3.time.scale().range([0, width], .1);
x.domain([
  d3.min(dadosAcessos, function(d) {
    return d.date.setDate(d.date.getDate() - 1);
  }),
  d3.max(dadosAcessos, function(d) {
    return d.date.setDate(d.date.getDate() + 2);
  })
]);

// y axis domain (ie: time)
y.domain([0, d3.max(dadosAcessos, function(d) {
  return d.acessos;
})]);

// Create brush for mini graph
var brush = d3.svg.brush()
  .x(x)
  .on("brush", brushed);

// Define the X axis
var xAxis = d3.svg.axis()
  .scale(x)
  .ticks(d3.time.months)
  .orient("bottom");

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

// Add the brush
graph.append("g")
  .attr("class", "x brush")
  .call(brush)
  .selectAll("rect")
  .attr("y", -10)
  .attr("height", height + 15);

// Add the Y axis
graph.append("g")
  .attr("class", "y axis")
  .attr("transform", "translate(0,0)")
  .call(yAxis)
  .append("text")
  .attr("transform", "rotate(-90)")
  .attr("y", 6)
  .attr("dy", ".71em")
  .style("text-anchor", "end")
  .text("Acessos")
  .attr("class", "y_label");

var bar = graph.selectAll(".bars")
  .data(nestByDate)
  .enter()
  .append("g");

bar.selectAll("rect")
  .data(function(d) {
    return d.values;
  })
  .enter().append("rect")
  .attr("width", function(d) {
    return width / (len * 2);
  })
  .attr("x", function(d) {
    return x(d.date.setDate(d.date.getDate() + 1)) - (width / len) / 2;
  })
  .attr("y", function(d) {
    return y(d.y1);
  })
  .attr("fill", function(d) {
    return color(d.fullname);
  })
  .attr("height", function(d) {
    return y(d.y0) - y(d.y1);
  });

function brushed() {
  var dataIni = new Date(brush.extent()[0]);
  var dataFim = new Date(brush.extent()[1]);
  console.log("BRUSH");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>


<div id="acessos"></div>

Augusto

RESOLVED

I'm changed these lines to fix the problem...

var x = d3.scale.ordinal().rangeRoundBands([0, width], .05);
x.domain(dadosAcessos.map(function(d){ return d.date; }));

bar.selectAll("rect")
.data(function(d) {
  return d.values;
})
.enter().append("rect")
.attr("width", function(d) {
  return x.rangeBand();
})
.attr("x", function(d,i) {
  d.x = x(d.date);
  return x(d.date);
})
.attr("y", function(d) {
  return y(d.y1);
})
.attr("fill", function(d) {
  return color(d.fullname);
})
.attr("height", function(d) {
    return y(d.y0) - y(d.y1);
})

Thank's a lot!!

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Stacked Bar Chart Labels - D3

분류에서Dev

Label stacked bar chart with variable other than plotted Y

분류에서Dev

stacked bar and line chart in same graph with any android library?

분류에서Dev

How to change section color of a stacked bar chart in Google Charts API?

분류에서Dev

Highcharts - Detail chart with stacked columns

분류에서Dev

Dimple.js - Add data labels to each bar of the bar chart

분류에서Dev

vertical bar chart with validation

분류에서Dev

AndroidPlot - Stacked Bar Z-order

분류에서Dev

Flot Bar Chart Data Conversion

분류에서Dev

Subset ordinal domain for a bar chart

분류에서Dev

Flot Chart's Bar Width

분류에서Dev

Custom bar chart text with Highcharts

분류에서Dev

Why do Chart Stacked Columns show up as thin lines?

분류에서Dev

How do I display multiple stacked columns for each date range in an stacked Bar

분류에서Dev

Pandas stacked bar creating many individual plots with incorrect bottom values

분류에서Dev

R ggplot How to plot a bar chart with different colours inside depicting 3 differents columns from the dataframe?

분류에서Dev

Programatically disable series on nvd3 Horizontal Multi-Bar Chart

분류에서Dev

NVD3 Line Plus Bar Chart X-Axis Ticks 잘못된 정렬

분류에서Dev

How to create a bar chart/histogram with bar per discrete value?

분류에서Dev

Horizontal bar chart y axis alignment

분류에서Dev

Why does stacked bar plot change when add facet in r ggplot2

분류에서Dev

Excel Graph: how can I show two values in the same bar? Not using stacked?

분류에서Dev

How to show a column with the value Zero in Bar chart in Highcharts?

분류에서Dev

Adding Grid to D3.js Line Chart

분류에서Dev

df.groupby ( 'MONTH') [ 'TASKTYPE']. value_counts (). unstack (). loc [month_order] .plot.bar (stacked = True)-KeyError

분류에서Dev

nvd3.js를 사용하여 Line Plus Bar Chart에 더 많은 라인을 넣으려면 어떻게해야합니까?

분류에서Dev

2dimple.js/d3.js auto size chart when window size changes

분류에서Dev

D3js d.x is undefined

분류에서Dev

How can I draw an additional horizontal grid line with a specific value in Google Bar chart (Not average value)

Related 관련 기사

  1. 1

    Stacked Bar Chart Labels - D3

  2. 2

    Label stacked bar chart with variable other than plotted Y

  3. 3

    stacked bar and line chart in same graph with any android library?

  4. 4

    How to change section color of a stacked bar chart in Google Charts API?

  5. 5

    Highcharts - Detail chart with stacked columns

  6. 6

    Dimple.js - Add data labels to each bar of the bar chart

  7. 7

    vertical bar chart with validation

  8. 8

    AndroidPlot - Stacked Bar Z-order

  9. 9

    Flot Bar Chart Data Conversion

  10. 10

    Subset ordinal domain for a bar chart

  11. 11

    Flot Chart's Bar Width

  12. 12

    Custom bar chart text with Highcharts

  13. 13

    Why do Chart Stacked Columns show up as thin lines?

  14. 14

    How do I display multiple stacked columns for each date range in an stacked Bar

  15. 15

    Pandas stacked bar creating many individual plots with incorrect bottom values

  16. 16

    R ggplot How to plot a bar chart with different colours inside depicting 3 differents columns from the dataframe?

  17. 17

    Programatically disable series on nvd3 Horizontal Multi-Bar Chart

  18. 18

    NVD3 Line Plus Bar Chart X-Axis Ticks 잘못된 정렬

  19. 19

    How to create a bar chart/histogram with bar per discrete value?

  20. 20

    Horizontal bar chart y axis alignment

  21. 21

    Why does stacked bar plot change when add facet in r ggplot2

  22. 22

    Excel Graph: how can I show two values in the same bar? Not using stacked?

  23. 23

    How to show a column with the value Zero in Bar chart in Highcharts?

  24. 24

    Adding Grid to D3.js Line Chart

  25. 25

    df.groupby ( 'MONTH') [ 'TASKTYPE']. value_counts (). unstack (). loc [month_order] .plot.bar (stacked = True)-KeyError

  26. 26

    nvd3.js를 사용하여 Line Plus Bar Chart에 더 많은 라인을 넣으려면 어떻게해야합니까?

  27. 27

    2dimple.js/d3.js auto size chart when window size changes

  28. 28

    D3js d.x is undefined

  29. 29

    How can I draw an additional horizontal grid line with a specific value in Google Bar chart (Not average value)

뜨겁다태그

보관