【发布时间】:2017-02-28 11:12:48
【问题描述】:
我正在尝试使用 dc.js 创建堆叠条形图,如下所示:
数据:
<pre id="data">
Status,StatusT,Phase,PhaseT,CompletionDate,CalMonth,Sales,SalesCount
3,Won,Z04,Decide,20130101,201012,2203262.13,1
3,Won,Z04,Decide,20130101,201111,607933.8,1
3,Won,Z05,Deliver,20131001,201202,66.08,1
3,Won,Z04,Decide,20120501,201202,66.08,1
3,Won,Z01,Understand,20120409,201203,65.07,1
3,Won,Z04,Decide,20121231,201204,4645214.7,1
3,Won,Z05,Deliver,20130918,201204,66.52,1
3,Won,Z04,Decide,20130418,201204,2312130.92,1
3,Won,Z05,Deliver,20120504,201205,68.07,1
3,Won,Z05,Deliver,20120504,201205,515994.86,1
3,Won,Z04,Decide,20120504,201205,68.07,1
3,Won,Z04,Decide,20120504,201205,68.07,1
</pre>
Javascript:
var dateFormat = d3.time.format('%Y%m%d');
var monthNameFormat = d3.time.format("%b-%Y");
// Prepare Data
for (var z = 0; z < opportunities.length; z++) {
opportunities[z].DD = dateFormat.parse(opportunities[z].CompletionDate);
}
opportunities.sort(function(a,b){
return b.DD - a.DD;
});
var ndx = crossfilter(opportunities);
var dimMonthYear = ndx.dimension(function(d) {
//return d.CompletionDate
return monthNameFormat(new Date(d.DD));
});
var phaseUnderstand = dimMonthYear.group().reduceSum(function(d) {
if (d.Phase === "Z01") {
return d.Sales;
} else {
return 0;
}
});
var phasePropose = dimMonthYear.group().reduceSum(function(d) {
if (d.Phase === "Z02") {
return d.Sales;
} else {
return 0;
}
});
var phaseNegotiate = dimMonthYear.group().reduceSum(function(d) {
if (d.Phase === "Z03") {
return d.Sales;
} else {
return 0;
}
});
var phaseDecide = dimMonthYear.group().reduceSum(function(d) {
if (d.Phase === "Z04") {
return d.Sales;
} else {
return 0;
}
});
var phaseDeliver = dimMonthYear.group().reduceSum(function(d) {
if (d.Phase === "Z05") {
return d.Sales;
} else {
return 0;
}
});
chart
.width(768)
.height(480)
.margins({
left: 80,
top: 20,
right: 10,
bottom: 80
})
.x(d3.scale.ordinal())
.round(d3.time.month.round)
.alwaysUseRounding(true)
.xUnits(dc.units.ordinal)
.brushOn(false)
.xAxisLabel('Months')
.yAxisLabel("Expected Sales (in thousands)")
.dimension(dimMonthYear)
.renderHorizontalGridLines(true)
.renderVerticalGridLines(true)
// .barPadding(0.1)
//.outerPadding(0.05)
.legend(dc.legend().x(130).y(30).itemHeight(13).gap(5))
.group(phaseUnderstand, "Understand")
.stack(phasePropose, "Propose")
.stack(phaseNegotiate, "Negotiate")
.stack(phaseDecide, "Decide")
.stack(phaseDeliver, "Deliver")
.centerBar(true)
.elasticY(true)
.elasticX(true)
.renderlet(function(chart) {
chart.selectAll("g.x text").attr('dx', '-30').attr(
'dy', '-7').attr('transform', "rotate(-60)");
});
chart.render();
我能够渲染图表,但我无法按月按升序对 X 轴进行排序并使其沿 X 轴具有弹性。如果我只使用日期,那么图表会变得过于详细(尽管 x 轴仍然没有弹性),这对于我创建它的目的没有用。这是一个示例小提琴:https://jsfiddle.net/NewMonk/1hbjwxzy/67/。
【问题讨论】:
标签: javascript d3.js dc.js crossfilter stacked-chart