如何在dc.js中过滤堆积条形图后更改颜色

时间:2014-05-03 11:17:15

标签: javascript dc.js

我尝试在crossfilter之后更改bar的颜色,它的工作是crossfilter但是我想要更改filter的过滤器的coloe.i尝试下面的代码。

 {% extends "base.html" %}
 {% load staticfiles %}
 {% block content %}
 <head>
 <style>
    div{
       background:#faebcc;
    }
 </style>
 <link href="{% static 'dc/css/dc.css' %}"  rel="stylesheet" media="screen">
 <link href="{% static 'dc/css/example-styles.css' %}"  rel="stylesheet" media="screen">
 </head>
  <body>
   <div class="container">
     <div  class="col-lg-6">
    <h3>Map wise selection of US</h3>
   <div id="us-chart"  STYLE="width: 100%;"></div>
   </div>


       <div class=col-lg-6>
       <h3>Top 10 Counties</h3>
   <div id="const"></div>
        </div>




  </div>
  <div class="container">
         <h2>Age wise population of US</h2>
             <div id="chart" class="col-lg-8"></div>


    </div>


   <div class="container" style="margin-top: 25px" class="col-lg-12">

   <div class=col-lg-12>
       <h3>States of US</h3>
   <div id="chart-row-Population_Density">
    </div>
   </div>
   </div>
  <!-- <div class="container" class="col-lg-12">
    <div id="industry-chart" ></div>
   </div>-->
   <div class="container" class="col-lg-12">
    <div id="county_linet" ></div>
   </div>
   <!--<div class="container" class="col-lg-8">
   <div id="round-chart" ></div>
   </div>-->




    <script type="text/javascript" src="{% static 'dc/js/d3.js' %}"></script>
 <script type="text/javascript" src="{% static 'dc/js/crossfilter.js' %}"></script>
 <script type="text/javascript"  src="{% static 'dc/js/dc.js' %}"></script>
 <script type="text/javascript"  src="{% static 'dc/js/bootstrap.min.js' %}"></script>
 <script type="text/javascript"   src="{% static 'dc/js/d3.js' %}"></script>
 <script type="text/javascript"   src="{% static 'dc/js/index.js' %}"></script>
 <script type="text/javascript">

var numberFormat = d3.format(".2f");
var stacked = dc.barChart("#chart");
var constRowChart=dc.rowChart("#const");
 var usChart = dc.geoChoroplethChart("#us-chart");
 var industryChart = dc.bubbleChart("#industry-chart");
 var roundChart = dc.bubbleChart("#round-chart");
 var barchart= dc.barChart("#chart-row-Population_Density");
 var chart=dc.pieChart("#p");
 var lineChart = dc.lineChart("#county_linet");
 d3.csv("{% static 'healthdata1.csv' %}", function(error, csv) {

 function resize() {


// adjust things when the window size changes
width = parseInt(d3.select('#us-chart').style('width'));
width = width - margin.left - margin.right;
height = width * mapRatio;

// update projection
projection
    .translate([width / 2, height / 2])
    .scale(width);

// resize the map container
usChart
        .width(width)
        .height(height);

// resize the map
usChart.selectAll('.state').attr('d', path);
}

var dateFormat = d3.time.format("%Y");
var numberFormat = d3.format(",f");


 var data = crossfilter(csv);


     var barTip = d3.tip()
    .attr('class', 'd3-tip')
    .offset([-10, 0])
    .html(function (d) {
        return "<span style='color: #f0027f'>" + d.data.key + "</span> : " + d.y.toFixed(0);
    });


    var states = data.dimension(function (d) {
        return d["State_Id"];
    });
    var stateRaisedSum = states.group().reduceSum(function (d) {
        return d["Population"];
    });

    var industries = data.dimension(function (d) {
        return d["County_Name"];
    });

     var inds= industries.group().reduceSum(function (d){
    return d["poverty"];
});


var stateDim=data.dimension(function (d){
    return d["State_Name"];
});

var density = data.dimension(function (d) {
        return d["County_Name"];
    });

var const_total= density.group().reduceSum(function (d){
    return d["Population"];
});


 var Population_tot= stateDim.group().reduceSum(function (d){
    return  d["Population"];
});

    var statsByIndustries = industries.group().reduce(
            function (p, v) {
                p.amountRaised += +v["Population_Density"];
                p.deals += +v["Poverty"];
                return p;
            },
            function (p, v) {
                p.amountRaised -= +v["Population_Density"];
               // if (p.amountRaised < 0.001) p.amountRaised = 0; // do some clean up
                p.deals -= +v["Poverty"];
                return p;
            },
            function () {
                return {amountRaised: 0, deals: 0}
            }
    );

    var rounds = data.dimension(function (d) {
        return d["County_Name"];
    });
    var statsByRounds = rounds.group().reduce(
            function (p, v) {
                p.amountRaised += +v["Poverty"];
                p.deals += +v["Population"];
                return p;
            },
            function (p, v) {
                p.amountRaised -= +v["Poverty"];
                //if (p.amountRaised < 0.001) p.amountRaised = 0; // do some clean up
                p.deals -= +v["Population"];
                return p;
            },
            function () {
                return {amountRaised: 0, deals: 0}
            }
    );
    var margin = {top: 10, left: 10, bottom: 10, right: 10}
    , width = parseInt(d3.select('#us-chart').style('width'))
    , width = width - margin.left - margin.right
    , mapRatio = .6
    , height = width * mapRatio;

var projection = d3.geo.albersUsa()
    .scale(width)
    .translate([width / 2, height / 2]);

var path = d3.geo.path()
.projection(projection);

d3.select(window).on('resize', resize);

  d3.json("{% static 'us-states.json' %}", function(error, statesJson) {
        usChart.width(width)
                .height(height)
                .dimension(states)
                .projection(projection)
                .group(stateRaisedSum)
                .colors(d3.scale.quantize().range(["#E2F2FF", "#C4E4FF", "#9ED2FF", "#81C5FF",     "#6BBAFF", "#51AEFF", "#36A2FF", "#1E96FF", "#0089FF", "#0061B5"]))
                .colorDomain([0, 200])
                .colorCalculator(function (d) { return d ? usChart.colors()(d) : '#ccc'; })
                .overlayGeoJson(statesJson.features, "state", function (d) {
                    return d.properties.name;
                })
                .title(function (d) {
                    return "State: " + d.key + "\nTotal Population: " + d.value;
                });

        industryChart.width(1100)
                .height(400)
                .margins({top: 10, right: 50, bottom: 30, left: 60})
                .dimension(industries)
                .group(statsByIndustries)
                .colors(d3.scale.category10())
                .keyAccessor(function (p) {
                    return p.value.amountRaised;
                })
                .valueAccessor(function (p) {
                    return p.value.deals;
                })
                .radiusValueAccessor(function (p) {
                    return p.value.amountRaised;
                })
                .x(d3.scale.linear().domain([0, 5000]))
               // .y(d3.scale.linear().domain([0.10, 500]))
                .r(d3.scale.linear().domain([0, 50000]))
                .minRadiusWithLabel(10)
                .elasticY(true)
                .yAxisPadding(100)
                .elasticX(true)
                .xAxisPadding(200)
                .maxBubbleRelativeSize(0.08)
                .renderHorizontalGridLines(true)
                .renderVerticalGridLines(true)
                .renderLabel(true)
                .renderTitle(true)

                .title(function (p) {

                  return p.key
                            + "\n"
                            + "Population Density: " + numberFormat(p.value.amountRaised) + "\n"
                            + "Percentage of Poverty: " + numberFormat(p.value.deals);
                });

        industryChart.yAxis().tickFormat(function (s) {
            return s + " deals";
        });
        industryChart.xAxis().tickFormat(function (s) {
            return s + "M";
        });



     barchart.width(1100)
    .height(350)
    .margins({ top: 10, left: 50, right: 10, bottom: 80 })
    .transitionDuration(750)
    .xAxisLabel('States of US')
    .yAxisLabel('Population')
    .dimension(stateDim)
    .group(Population_tot)
    .centerBar(false)
    .brushOn(false)
    .title(function (d) {
        ""
    })
    .gap(5)
    .elasticY(true)
    .colors(['#00FF00'])
    .xUnits(dc.units.ordinal)
    .x(d3.scale.ordinal())
    .y(d3.scale.linear().domain([0, 600]))
    .renderHorizontalGridLines(false)
    .yAxis().tickFormat(d3.format("s"));

 barchart.renderlet(function (chart) {
    chart.selectAll("g.x text").attr('dx', '-30').attr('dy', '-7').attr('transform', "rotate(-60)");
});

       var eventsByDate = stateDim.group().reduce(
        function (p, v) {
            // ++p.Count;
            p.Age_19_Under += +v["Age_19_Under"];
            p.Age_19_64 += +v["Age_19_64"];
            p.Age_65_84 += +v["Age_65_84"];
            p.Age_85_and_Over += +v["Age_85_and_Over"];
            return p;
        },
        function (p, v) {
           //   --p.Count;
            p.Age_19_Under -= -v["Age_19_Under"];
            p.Age_19_64 -= -v["Age_19_64"];
            p.Age_65_84 -=  -v["Age_65_84"];
            p.Age_85_and_Over += -v["Age_85_and_Over"];
            return p;
        },
        function () {
            return {
                // Count: 0,
                Age_19_Under: 0,
                Age_19_64: 0,
                Age_65_84: 0,
                Age_85_and_Over:0
            };
        }
);

var colorRenderlet = function (chart) {
    chart.selectAll("rect.bar")
            .on("click", function (d) {
                function setAttr(selection, keyName) {
                    selection.style("fill", function (d) {
                        if (d[keyName] == "Age_19_Under") return "#63D3FF";
                        else if (d[keyName] == "Age_19_64") return "#FF548F";
                        else if (d[keyName] == "Age_65_84") return "#9061C2";
                         else if (d[keyName] == "Age_85_and_Over") return "#00FF00";
                    });
                }
                setAttr(_chart.selectAll("g.stack").selectAll("rect.bar"), "layer");
                setAttr(_chart.selectAll("g.dc-legend-item").selectAll("rect"), "name")
            });
};

 stacked
        .margins({top: 50, right: 20, left: 50, bottom: 50})
        .width(1100)
        .height(350)
        .gap(5)
        .dimension(states)
        .group(eventsByDate,"Age(Under 19)")
        .valueAccessor(function (d) {
            return d.value.Age_19_Under;
        })
        .stack(eventsByDate, "Age(19-64)", function (d) {
            return d.value.Age_19_64;
        })
        .stack(eventsByDate, "Age(65-84)", function (d) {
            return d.value.Age_65_84;
        })
        .stack(eventsByDate, "Age(85 and Over)", function (d) {
            return d.value.Age_85_and_Over;
        })
        .y(d3.scale.linear().domain([0, 600]))
        .xUnits(dc.units.ordinal)
        .x(d3.scale.ordinal())

        .centerBar(true)
        .elasticY(true)
        .brushOn(false)
        .transitionDuration(750)
        .renderlet(colorRenderlet)

       .legend(dc.legend().x(100).y(0).itemHeight(13).gap(5));




    stacked.renderlet(function (chart) {
    chart.selectAll("g.x text").attr('dx', '-30').attr('dy', '-7').attr('transform', "rotate(-60)");
});

        roundChart.width(1100)
                .height(400)
                .margins({top: 10, right: 50, bottom: 30, left: 60})
                .dimension(rounds)
                .group(statsByRounds)
                .colors(d3.scale.category10())
                .keyAccessor(function (p) {
                    return p.value.amountRaised;
                })
                .valueAccessor(function (p) {
                    return p.value.deals;
                })
                .radiusValueAccessor(function (p) {
                    return p.value.amountRaised;
                })
                .x(d3.scale.linear().domain([0, 5000]))
                .r(d3.scale.linear().domain([0, 50000]))
                .minRadiusWithLabel(15)
                .elasticY(true)
                .yAxisPadding(150)
                .elasticX(true)
                .xAxisPadding(300)
                .maxBubbleRelativeSize(0.07)
                .renderHorizontalGridLines(true)
                .renderVerticalGridLines(true)
                .renderLabel(true)
                .renderTitle(true)
                .title(function(p){
                    return p.key
                            + "\n"
                            + "Amount Raised: " + numberFormat(p.value.amountRaised) + "M\n"
                            + "Number of Deals: " + numberFormat(p.value.deals);
                });
        roundChart.yAxis().tickFormat(function (s) {
            return s + " deals";
        });
        roundChart.xAxis().tickFormat(function (s) {
            return s + "M";
        });
    constRowChart.width(300)
    .height(300)
    .margins({top: 20, left: 120, right: 10, bottom: 20})
    .transitionDuration(750)
    .dimension(density)
    .group(const_total)
    .renderLabel(true)
    .gap(1)
    .title(function (d) {
        return "";
    })
    .elasticX(true)
    .colors(d3.scale.category20c())
    .xAxis().ticks(3).tickFormat(function (s) {
            return s;
});

constRowChart.data(function (group) {


    return group.top(10);
});


 lineChart.width(860)
.height(350)
.margins({top: 10, right: 10, bottom: 90, left: 50})
.dimension(industries)
.group(inds)
.xAxisLabel('States of US')
.yAxisLabel('Poverty in US')
.transitionDuration(750)
.elasticY(true)
.brushOn(false)
.colors(['#00FFFF'])
.xUnits(dc.units.ordinal)
.x(d3.scale.ordinal())
.y(d3.scale.linear().domain([100, 1600]))
.renderHorizontalGridLines(false)
//.yAxis().tickFormat(d3.format("s"))

/ * .valueAccessor(function(d){                     返回d.value;                 })* /     .title伪(函数(d){       返回&#34; &#34; + d.key +&#34; :&#34; + d.value.toFixed(2);

  })

//.x(d3.scale.linear().domain([4, 27]))
.xAxis();
 lineChart.renderlet(function (chart) {
    chart.selectAll("g.x text").attr('dx', '-30').attr('dy', '-7').attr('transform', "rotate(-60)");
});




       dc.renderAll();
       d3.selectAll(".bar").call(barTip);
       d3.selectAll(".bar").on('mouseover', barTip.show)
       .on('mouseout', barTip.hide);


    });





  });



</script>
   </body>
{% endblock %}

那我能为此做些什么呢?

1 个答案:

答案 0 :(得分:0)

这开始是很多代码(恭喜!),我不太确定问题是什么。如果您要询问过滤后的 out 条的颜色,我想您会在CSS中找到答案。

如果您想知道为什么渲染器不起作用,请尝试在渲染中设置断点并查看selectAll是否返回您期望的选择。