dc.js 饼图为空

dc.js pie chart is empty

我正在尝试 link 将饼图转换为地图,这样当您单击某个州时,饼图会随着对该州的普遍投票而更新。

目前我的饼图显示为空。

Csv 的格式如下:

state, party, votes
Alabama,dem,725704
Alabama,rep,1314431
Alabama,lib,44211
Alabama,gre,20276
Alabama,con,9341
Alaska,dem,116454
Alaska,rep,163387
Alaska,lib,18725
Alaska,gre,5735
Alaska,con,3866
Alaska,other,10441

我的代码:

d3.csv("elecVotes.csv", function (data) {
    d3.json("us.json", function (json){

       // set up crossfilter on the data.
        var ndx = crossfilter(data);

    // set up the dimensions
        var stateDim = ndx.dimension(function (d) { return d.state; });
        var party = partyDim.group().reduceSum(function(d) { return d.votes;});
        var votesDim = ndx.dimension(function(d) { return d.votes; });

    // set up the groups/values
        var state = stateDim.group();
        var party = partyDim.group(); 
        var votes = votesDim.group();

    // the 4 different charts - options are set below for each one.
        var pie = dc.pieChart('#chart-pie');
        var usmap = dc.geoChoroplethChart("#usmap");

    //create pie from to show popular vote for each state
        pie
        .width(180)
        .height(180)
        .radius(80)
        .dimension(partyDim)
        .group(votes)
        .renderLabel(true)
        .innerRadius(10)
        .transitionDuration(500)
        .colorAccessor(function (d, i) { return d.value; });

    //display US map                    
        usmap
        .width(900)
        .height(500)
        .dimension(stateDim)
        .group(state)
        .colors(["rgb(20,202,255)","rgb(144,211,035)"])
        .overlayGeoJson(json.features, "name", function (d) { return d.properties.name; })      


        // at the end this needs to be called to actually go through and generate all the graphs on the page.
        dc.renderAll();
    }); 
    });             

我不确定我做错了什么

我不认为你想要一个 votesDim - 它会按票数分组,所以你最终可能会为每个计数得到不同的 bin,因为它们可能是唯一的。

我猜你可能想计算每个政党的票数,所以:

var partyGroup = partyDim.group().reduceSum(function(d) { return d.votes; });

请记住,维度指定您要过滤的内容,而组是聚合和读取数据的地方。

您还需要在开始之前显式转换任何数字,因为 d3.csv 会将每个字段作为字符串读取。所以:

data.forEach(function(r) {
  r.votes = +r.votes;
});
var ndx = crossfilter(data);

不确定这是否有助于解决您的问题。请注意,这实际上与地图无关;饼图应该能够独立于地图的作用自行绘制。

编辑

我敢打赌问题出在列名中的空格。这样你就可以很容易地得到名为 " party"" votes" 的字段...