在一页中显示饼图,分组和堆积条形图

时间:2014-07-03 08:34:29

标签: javascript d3.js charts

我想在一个页面中显示两个图表。饼图显示但不显示分组和堆积条形图。我试图更改Id名称,但没有运气:(。如果有人帮我修改代码,我会很感激。

/ *在一个页面中显示矩阵图表,饼图,分组和堆积条形图* /

<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 个答案:

答案 0 :(得分:0)

首先,正如我们在此处讨论的那样(d3 Donut chart does not render),您应该定位

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

在剧本上方。

第二,你错过了你的第二个svg声明中的#来正确选择div的id,它必须是

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

你也可以考虑以不同方式命名第二个svg(例如svg2),这样你就不会覆盖你的第一个svg变量(以防你以后想要用它做什么)。