javascript DC-js中的多系列条形图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21961551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multi-series bar chart in DC-js
提问by amcdnl
I'm using DC.js( lib on top of D3 ) and have a great example of a single series bar chart:
我正在使用DC.js( D3 之上的 lib )并且有一个很好的单系列条形图示例:
var xf = crossfilter(data);
var dim = xf.dimension(function (d) { return d["EmployeeName"]; });
var group = dim.group().reduceSum(function (d) { return d["AverageSale"]; });
var chart = dc.barChart(elm);
chart.barPadding(0.1)
chart.outerPadding(0.05)
chart.brushOn(false)
chart.x(d3.scale.ordinal());
chart.xUnits(dc.units.ordinal);
chart.elasticY(true);
chart.dimension(dim).group(group);
chart.render();
but I was wondering if it was possible to create a multi dimensional bar chart using this library. For example: Group by Store Name then Group By Employee then y-axis display average sale value ( already calculated by my backend ).
但我想知道是否可以使用此库创建多维条形图。例如:按商店名称分组,然后按员工分组,然后 y 轴显示平均销售额(已由我的后端计算)。
The data looks like:
数据看起来像:
[{
"EmployeeName": "Heather",
"StoreName" : "Plaza",
"AverageSaleValue": 200
}{
"EmployeeName": "Mellisa",
"StoreName" : "Plaza",
"AverageSaleValue": 240
}, {
"EmployeeName": "Sarah",
"StoreName" : "Oak Park",
"AverageSaleValue": 300
} ... ]
回答by DJ Martin
If you have a static number of groups to graph, you can achieve the desired effect with a composite chart.
如果要绘制静态数量的组,则可以使用复合图表实现所需的效果。
In the example below, I hard coded the gap between the bar charts - I can do this because I know there are 12 months being displayed.
在下面的示例中,我对条形图之间的间隙进行了硬编码 - 我可以这样做,因为我知道要显示 12 个月。
var actuals = dc.barChart(compositeChart)
.gap(65)
.group(group)
.valueAccessor(function (d) {
return d.value.Actual;
});
var budgets = dc.barChart(compositeChart)
.gap(65)
.group(group)
.valueAccessor(function (d) {
return d.value.Budget;
});
I pass these bar charts to the compose method of a composite chart:
我将这些条形图传递给复合图表的 compose 方法:
compositeChart
.width(1000)
.height(300)
.dimension(monthDimension)
.group(group)
.elasticY(true)
.x(d3.time.scale().domain(timeExtent))
.xUnits(d3.time.months)
.round(d3.time.month.round)
.renderHorizontalGridLines(true)
.compose([budgets, actuals])
.brushOn(true);
Finally, I add a renderlet to move one of the charts to the right a few pixels:
最后,我添加了一个 renderlet 来将其中一个图表向右移动几个像素:
compositeChart
.renderlet(function (chart) {
chart.selectAll("g._1").attr("transform", "translate(" + 20 + ", 0)");
chart.selectAll("g._0").attr("transform", "translate(" + 1 + ", 0)");
});
I know this isn't the cleanest approach but it can work in a pinch.
我知道这不是最干净的方法,但它可以在紧要关头工作。
I hope this helps.
我希望这有帮助。
回答by Ethan Jewett
The closest thing to what you're asking for that comes to mind immediately in dc.js would be a stacked bar chart (example). But I think what you might prefer is a grouped bar chart. I'm not sure that this chart type is currently supported by dc.js. Maybe someone else knows.
在 dc.js 中立即想到的与您要求的最接近的是堆积条形图(示例)。但我认为您可能更喜欢分组条形图。我不确定 dc.js 当前是否支持这种图表类型。也许别人知道。
回答by Moshe Quantz
I know I'm late for this but it might help someone else.
我知道我迟到了,但它可能会帮助其他人。
To create grouped-bar-chart in dc.js without overwrite the original dc code you can take advantage of ‘pretransition' event and split the bars to create a group.
要在 dc.js 中创建分组条形图而不覆盖原始 dc 代码,您可以利用 'pretransition' 事件并拆分条形以创建一个组。
I've created an example (jsfiddle)
The magic happens here:
魔法发生在这里:
let scaleSubChartBarWidth = chart => {
let subs = chart.selectAll(".sub");
if (typeof barPadding === 'undefined') { // first draw only
// to percentage
barPadding = BAR_PADDING / subs.size() * 100;
// each bar gets half the padding
barPadding = barPadding / 2;
}
let startAt, endAt,
subScale = d3.scale.linear().domain([0, subs.size()]).range([0, 100]);
subs.each(function (d, i) {
startAt = subScale(i + 1) - subScale(1);
endAt = subScale(i + 1);
startAt += barPadding;
endAt -= barPadding;
// polygon(
// top-left-vertical top-left-horizontal,
// top-right-vertical top-right-horizontal,
// bottom-right-vertical bottom-right-horizontal,
// bottom-left-vertical bottom-left-horizontal,
// )
d3.select(this)
.selectAll('rect')
.attr("clip-path", `polygon(${startAt}% 0, ${endAt}% 0, ${endAt}% 100%, ${startAt}% 100%)`);
});
};
...
...
.on("pretransition", chart => {
scaleSubChartBarWidth(chart);
})
Complete code:
完整代码:
markup
标记
<div id="chart-container"></div>
Js
JS
//'use strict';
let compositeChart = dc.compositeChart("#chart-container");
const BAR_PADDING = .1; // percentage the padding will take from the bar
const RANGE_BAND_PADDING = .5; // padding between 'groups'
const OUTER_RANGE_BAND_PADDING = 0.5; // padding from each side of the chart
let sizing = chart => {
chart
.width(window.innerWidth)
.height(window.innerHeight)
.redraw();
};
let resizing = chart => window.onresize = () => sizing(chart);
let barPadding;
let scaleSubChartBarWidth = chart => {
let subs = chart.selectAll(".sub");
if (typeof barPadding === 'undefined') { // first draw only
// to percentage
barPadding = BAR_PADDING / subs.size() * 100;
// each bar gets half the padding
barPadding = barPadding / 2;
}
let startAt, endAt,
subScale = d3.scale.linear().domain([0, subs.size()]).range([0, 100]);
subs.each(function (d, i) {
startAt = subScale(i + 1) - subScale(1);
endAt = subScale(i + 1);
startAt += barPadding;
endAt -= barPadding;
// polygon(
// top-left-vertical top-left-horizontal,
// top-right-vertical top-right-horizontal,
// bottom-right-vertical bottom-right-horizontal,
// bottom-left-vertical bottom-left-horizontal,
// )
d3.select(this)
.selectAll('rect')
.attr("clip-path", `polygon(${startAt}% 0, ${endAt}% 0, ${endAt}% 100%, ${startAt}% 100%)`);
});
};
let data = [
{
key: "First",
value: [
{key: 1, value: 0.18},
{key: 2, value: 0.28},
{key: 3, value: 0.68}
]
},
{
key: "Second",
value: [
{key: 1, value: 0.72},
{key: 2, value: 0.32},
{key: 3, value: 0.82}
]
},
{
key: "Third",
value: [
{key: 1, value: 0.3},
{key: 2, value: 0.22},
{key: 3, value: 0.7}
]
},
{
key: "Fourth",
value: [
{key: 1, value: 0.18},
{key: 2, value: 0.58},
{key: 3, value: 0.48}
]
}
];
let ndx = crossfilter(data),
dimension = ndx.dimension(d => d.key),
group = {all: () => data}; // for simplicity sake (take a look at crossfilter group().reduce())
let barChart1 = dc.barChart(compositeChart)
.barPadding(0)
.valueAccessor(d => d.value[0].value)
.title(d => d.key + `[${d.value[0].key}]: ` + d.value[0].value)
.colors(['#000']);
let barChart2 = dc.barChart(compositeChart)
.barPadding(0)
.valueAccessor(d => d.value[1].value)
.title(d => d.key + `[${d.value[1].key}]: ` + d.value[1].value)
.colors(['#57B4F0']);
let barChart3 = dc.barChart(compositeChart)
.barPadding(0)
.valueAccessor(d => d.value[2].value)
.title(d => d.key + `[${d.value[2].key}]: ` + d.value[2].value)
.colors(['#47a64a']);
compositeChart
.shareTitle(false)
.dimension(dimension)
.group(group)
._rangeBandPadding(RANGE_BAND_PADDING)
._outerRangeBandPadding(OUTER_RANGE_BAND_PADDING)
.x(d3.scale.ordinal())
.y(d3.scale.linear().domain([0, 1]))
.xUnits(dc.units.ordinal)
.compose([barChart1, barChart2, barChart3])
.on("pretransition", chart => {
scaleSubChartBarWidth(chart)
})
.on("filtered", (chart, filter) => {
console.log(chart, filter);
})
.on("preRedraw", chart => {
chart.rescale();
})
.on("preRender", chart => {
chart.rescale();
})
.render();
sizing(compositeChart);
resizing(compositeChart);
It's not perfect but it could give a starting point.
它并不完美,但可以提供一个起点。
回答by Rajesh Rajamani
I was able to do this with a twist of the renderlet technique in the following link renderlet function for coloring
我能够通过在以下链接渲染函数中对渲染技术进行着色来做到这一点
My code goes as follows
我的代码如下
.renderlet(function (chart) {
chart.selectAll('rect.bar').each(function(d){
d3.select(this).attr("fill",
(function(d){
var colorcode ="grey"
if(d.x[1] === "Zone1")
colorcode ="#ff7373";
else if(d.x[1] === "Zone2")
colorcode ="#b0e0e6";
else if(d.x[1] === "Zone3")
colorcode ="#c0c0c0";
else if(d.x[1] === "Zone4")
colorcode ="#003366";
else if(d.x[1] === "Zone5")
colorcode ="#ffa500";
else if(d.x[1] === "Zone6")
colorcode ="#468499";
else if(d.x[1] === "Zone7")
colorcode ="#660066";
return colorcode;
}))
});
});
Note : I was using a dimension with 2 values for the series .
注意:我为系列使用了具有 2 个值的维度。