0

I want to display two charts in one page.The Pie chart gets displayed but the Grouped and Stacked bar chart is not displaying . I tried to change the Id name in but no luck :( . Will appreciate if anyone helps me with the code correction .

/* Display Matrix Chart ,Pie chart, Grouped and Stacked bar chart in one page */

<apex:page showHeader="false">

    <apex:includeScript value="{!URLFOR($Resource.jquery1)}"/>    
    <apex:includeScript value="{!URLFOR($Resource.D3)}"/>
    <apex:includeScript value="{!URLFOR($Resource.nvD3)}"/> 

  <div id="body"  height="50%" width="100px" ></div>  // Id for Pie chart
  <div id="body1" height="30%" width="90px"></div>  // Id for Stacked and Grouped bar chart

<script>

// Matrix Chart starts here 
  var drawChart = function(divId,matrixReportId) {

        $.ajax('/services/data/v29.0/analytics/reports/'+matrixReportId,
            {
                    beforeSend: function(xhr) {
                    xhr.setRequestHeader('Authorization', 'Bearer {!$Api.Session_ID}');
                },

                success: function(response) {
                    console.log(response);

                 var chart = nv.models.multiBarChart();
                    var chartData = [];

                    document.getElementById(divId).innerHTML = '';

                    $.each(response.groupingsDown.groupings, function(di, de) {
                        var values = [];
                        chartData.push({"key":de.label, "values": values});
                        $.each(response.groupingsAcross.groupings, function(ai, ae) {
                            values.push({"x": ae.label, "y": response.factMap[de.key+"!"+ae.key].aggregates[0].value});
                        });
                    });
                    d3.select('#'+divId).datum(chartData).transition().duration(100).call(chart);
                    window.setTimeout(function(){ 
                        drawChart(divId,matrixReportId);
                    }, 5000);
                }
            }
        );
 };
 $(document).ready(function(){ 
   drawChart('chart','00O90000005SSHv');
 });

 //  Pie Chart Starts here

   var width =250 ,
    height = 450,
    radius = Math.min(width, height) / 2;

    var data = [{"age":"<5","population":2704659},{"age":"14-17","population":2159981},
        {"age":"14-17","population":2159981},{"age":"18-24","population":3853788},
        {"age":"25-44","population":14106543},{"age":"45-64","population":8819342},
        {"age":">65","population":612463}];

    var color = d3.scale.ordinal()
        .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);

     var arc = d3.svg.arc().outerRadius(radius - 10).innerRadius(0);

    var pie = d3.layout.pie()
        .sort(null)
        .value(function(d) { return d.population; });

    var svg = d3.select("#body").append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");


      var g = svg.selectAll(".arc")
          .data(pie(data))
        .enter().append("g")
          .attr("class", "arc");

      g.append("path")
          .attr("d", arc)
          .style("fill", function(d) { return color(d.data.age); });

      g.append("text")
          .attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
          .attr("dy", ".35em")
          .style("text-anchor", "middle")
          .text(function(d) { return d.data.age; });


 //  Grouped and Stacked Bar Chart starts here

     var n = 2, // number of layers
        m = 10, // number of samples per layer
        stack = d3.layout.stack(),
        layers = stack(d3.range(n).map(function() { return bumpLayer(m, .1); })),
        yGroupMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y; }); }),
        yStackMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y0 + d.y; }); });

     var margin = {top: 40, right: 10, bottom: 20, left: 10},
        width = 960 - margin.left - margin.right,
        height = 500 - margin.top - margin.bottom;

     var x = d3.scale.ordinal()
        .domain(d3.range(m))
        .rangeRoundBands([0, width], .08);

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

    var color = d3.scale.linear()
        .domain([0, n - 1])
        .range(["#aad", "#556"]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .tickSize(0)
        .tickPadding(6)
        .orient("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 + ")");

    var layer = svg.selectAll(".layer")
        .data(layers)
      .enter().append("g")
        .attr("class", "layer")
        .style("fill", function(d, i) { return color(i); });

    var rect = layer.selectAll("rect")
        .data(function(d) { return d; })
      .enter().append("rect")
        .attr("x", function(d) { return x(d.x); })
        .attr("y", height)
        .attr("width", x.rangeBand())
        .attr("height", 0);

    rect.transition()
        .delay(function(d, i) { return i * 10; })
        .attr("y", function(d) { return y(d.y0 + d.y); })
        .attr("height", function(d) { return y(d.y0) - y(d.y0 + d.y); });

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

    d3.selectAll("input").on("change", change);

    var timeout = setTimeout(function() {
      d3.select("input[value=\"grouped\"]").property("checked", true).each(change);
    }, 2000);

    function change() {
      clearTimeout(timeout);
      if (this.value === "grouped") transitionGrouped();
      else transitionStacked();
    }

    function transitionGrouped() {
      y.domain([0, yGroupMax]);

      rect.transition()
          .duration(500)
          .delay(function(d, i) { return i * 10; })
          .attr("x", function(d, i, j) { return x(d.x) + x.rangeBand() / n * j; })
          .attr("width", x.rangeBand() / n)
        .transition()
          .attr("y", function(d) { return y(d.y); })
          .attr("height", function(d) { return height - y(d.y); });
    }

    function transitionStacked() {
      y.domain([0, yStackMax]);

      rect.transition()
          .duration(500)
          .delay(function(d, i) { return i * 10; })
          .attr("y", function(d) { return y(d.y0 + d.y); })
          .attr("height", function(d) { return y(d.y0) - y(d.y0 + d.y); })
        .transition()
          .attr("x", function(d) { return x(d.x); })
          .attr("width", x.rangeBand());
    }

    // Inspired by Lee Byron's test data generator.
    function bumpLayer(n, o) {

      function bump(a) {
        var x = 1/(.1 + Math.random()),
            y = 2*Math.random()-.5,
            z = 10/(.1 + Math.random());
        for (var i = 0; i < n; i++) {
          var w = (i/n- y) * z;
          a[i] += x * Math.exp(-w * w);
        }
      }

      var a=[],i;
      for (i = 0; i < n; ++i) a[i] = o + o * Math.random();
      for (i = 0; i < 5; ++i) bump(a);
      return a.map(function(d, i) { return {x: i, y: Math.max(0, d)}; });
    }
    </script>
 <svg id="chart" height="50%" width="500px" ></svg>  // Id for Matrix chart
</apex:page>
Thanks in advance 

1 Answer 1

0

first, as we discussed here (d3 Donut chart does not render), you should position your

 <div id="body1" height="30%" width="90px"></div>

above the script.

second, you are missing the # in your second svg-declaration to correctly select the div by its id, it has to be

 var svg = d3.select("#body1").append("svg")

you could also think about naming the second svg differently (eg svg2) so you don't override your first svg-variable (in case you want to do something with it later).

6
  • Herbert,this is useful . But , what i'm trying now is Stacked and bar chart in first row , then in second row - Pie chart and matrix chart . But to my surprise all of them are showing it in seperate rows/divs . Have edited my code . So what this diplays is- first is Pie chart,second is Stacked and Grouped bar and lastly Matrix chart. Any pointer ? Jul 3, 2014 at 9:11
  • hm, not sure if i understand you correctly, but it sounds a little like its an issue with positioning? if that is the case, could you arrange your divs accordingly? one way the positioning is usually done is by creating a container div and then putting the other divs with the corresponding id inside this conainer, using css to arrange them. also, in your code, as far as i can see you now select the same div twice, once for the pie-chart, once for the bar-chart (twice #body and not #body1). Jul 3, 2014 at 11:07
  • Yes, its about positioning the charts. I tried adjusting it with divs but no luck so far.So 1st line the Staked and grouped chart on first line . 2nd line - two charts , one is Pie chart and second is Matrix chart . Tried with CSS but they are overlapping . Any recommandation with the code will be the best .Thanks Jul 3, 2014 at 12:31
  • ok, i put it in a fiddle: jsfiddle.net/99nuL - maybe it helps to play a little with the css. i think you should use the divs without height/width, as the appended svgs are larger than the boundaries you defined. if at all, these values should match. the matrix-chart does not get drawn, but that is probably due to the ajax-request. hope this helps. Jul 3, 2014 at 13:42
  • Sorry Herbert, was on leave. I'm so much thankful to you . This has really increased my knowledge . Its a bingo ! Jul 8, 2014 at 13:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.