1
votes

I have a bar chart with in dc.js. The x axis is dimension and y is the measure ranging from 1 - 10k. I want to show all the bars and their labels not overlapping each other. Chart looks fine when there are few bars when the number of bars starts to increase they look not okay. I am looking to auto resize the labels for the bar-chart.

Sample Chart enter image description here

I tried this method of renderlet to change the fontsize automatically

 stackedBarChart.on('renderlet', function(chart) {
             chart.selectAll('text.barLabel')
                 .attr('transform', function(d) {
                   //How do i get/set the width of the label here ?
                 });
1
I would hide the text and show it on hover (once you hover over the bar show the text). - ROOT
Its fine untill I dont export it as pdf, I would want to show them in pdf to show. - Shahabaz
There’s nothing built in to do that. I think you would need to count the number of bars (size of group.all()), and divide the chart width by that number to get the bar width. Then you could set the font size of the labels as some multiple of the bar width. This would work great in a pretransition hook. - Gordon
I just took a quick look and if you are using DCv4, the bar width is exposed as barChart._barWidth. Private members weren't exposed in earlier versions. - Gordon
I am using dc 3.1.5. I have also updated my question with what I tried to achieve the font size change can direct me a bit please ? - Shahabaz

1 Answers

1
votes

I tried the below and I am able to do dynamic label sizing. I used pretransistion and inside that fetched all bar lables and altered their font-size. The font sizing is altered according to Gordon's Idea, Getting each bar's size and and assigning the font size dynamically. For testing I have used .2 as a factor to reduce the font size.

   .on('pretransition', function(chart) {
         var chart_width = chart.width();
        chart.selectAll("text.barLabel").attr('font-size', function(data) {
            let total_bars = chart.group().all().length;
            let sing_bar_width = Math.floor(chart_width / total_bars);
            return (sing_bar_width * .2) + "px";
        });
    });