d3.js - 计算 dc.js 条形图中的条数

标签 d3.js dc.js

我想根据条形图上出现的条形数量调整条形图的宽度。这是我的图表,它显示了足够的记录,这些记录适合宽度并且显示得很好。 enter image description here

这是另一种场景,其中只有两个条形以相同的宽度显示,这看起来很奇怪。 enter image description here

对于这种情况,我需要根据条形的数量调整图表的宽度,这样我的图表就会看起来很漂亮。

这是我的脚本的一部分

var width = ??;   // Here how should I calculate width based on the number of bars? 
redrawCustomerCodeBarChart
        .width(width)
        .height(400)
        .margins({top: 10, right: 10, bottom: 70, left: 30})
        .dimension(customerNamer)
        .group(customerNameGroupr)
        .x(d3.scale.ordinal().domain(newCoh.map(function (d) {return d.customerName; })))
        .xUnits(dc.units.ordinal)
        .elasticY(true)
        .renderHorizontalGridLines(true)
        .on('renderlet',function(chart){
              chart.selectAll("g.x text")
                .attr('dx', '-15')
                .attr('transform', "rotate(-55)");
            })
         .on('filtered.monitor', function(d) {
               // return d.key + ' (' + d.value + ')';
               if(d.value !== undefined)
                size= d.value;
            })
        .controlsUseVisibility(true);

最佳答案

在大多数 dc.js 图表中,数据是从 group.all() 读取的。所以柱的数量就是简单的

customerNameGroupr.all().length

然后适当相乘。

如果条形的数量可能会随着内容的过滤而改变(例如使用remove_empty_bins),那么您需要在每次重绘之前设置宽度:

chart.on('preRedraw', function(chart) {
    chart.width(chart.group().all().length * BAR_WIDTH);
});

不过这可能会很困惑。

关于d3.js - 计算 dc.js 条形图中的条数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41143743/

相关文章:

javascript - D3 序数刻度,刻度值的左右边距

javascript - 开始使用 d3.js,需要哪些文件?

javascript - 如何在 dc.js 中为多标签数据制作行图

javascript - 如何在 d3.js 中将多个子元素附加到 div 中?

javascript - d3.js 如何简化复杂路径 - 使用自定义算法

javascript - 如何加载多个 csv 文件并将它们混合使用

javascript - 如何翻译 svg 元素本身?

d3.js - dc.js 系列图表上的反向 x 域

javascript - dc.js 根据第一个图表中的标准向多个图表中的数据点添加类

javascript - 如何在 dc.js 中禁用 rowChart 上的点击事件