How to remove weekends dates from x axis in dc js chart
Asked Answered
P

1

3

I have data for every date from Jan 2018 and I am creating a stacked line chart out of that data. Every weekend the count of my data is zero, so every weekend it shows a dip in my graph (as data reaches to zero). I want to avoid that dip. I have a Date column as well as a Day column. The Day column has values from 1 to 7 representing each day of week (1 is Monday and 7 is Sunday). Can I modify my x axis or graph to show only weekdays data?

Fiddle

var data = [
 { Type: 'T', Date: "2018-01-01", DocCount: 10, Day: 1},
 { Type: 'E', Date: "2018-01-01", DocCount: 10, Day: 1},
 ...
]

chart
.height(350)
.width(450)
.margins({top: 10, right: 10, bottom: 5, left: 35})
.dimension(dateDim)
.group(tGroup)
.stack(eGroup, "E")
.valueAccessor( function(d) {
    return d.value.count;
})
.transitionDuration(500)
.brushOn(false)
.elasticY(true)
.x(d3.time.scale().domain([minDateTime, maxDateTime]))
.xAxis().ticks(10).tickFormat(d3.format("s"));

enter image description here

Panto answered 23/6, 2018 at 13:17 Comment(0)
J
3

A time scale is always going to be very literal about how it maps dates to x coordinates. It has no notion of "skipping dates".

Instead, I would suggest using an ordinal scale for this purpose. With an ordinal scale, you decide exactly what the input and output values will be. dc.js will also help you out by automatically determining the input (domain) values.

Tell the chart to use an ordinal scale like this:

chart
.x(d3.scale.ordinal())
.xUnits(dc.units.ordinal)

Remove any empty dates like this. remove_empty_bins is from the FAQ but I modified it to look at the count element.

function remove_empty_bins(source_group) {
    return {
        all:function () {
            return source_group.all().filter(function(d) {
                //return Math.abs(d.value) > 0.00001; // if using floating-point numbers
                return d.value.count !== 0; // if integers only
            });
        }
    };
}
var nz_tGroup = remove_empty_bins(tGroup),
    nz_eGroup = remove_empty_bins(eGroup);
chart
.group(nz_tGroup)
.stack(nz_eGroup, "E")

Only question is, what if there is a weekday that happens not to have any data? Do you still want that to drop to zero? In that case I think you'd probably have to modify the filter in remove_empty_bins above.

weekdays only

Fork of your fiddle.

Julee answered 24/6, 2018 at 17:49 Comment(2)
Your solution works perfect. However I noticed that I have created the fiddle in d3 v3 and I am using d3 v4 in my actual problem so I modified d3.scale.ordinal() to d3.scaleOrdinal() but it is giving me error "unable to get property y of undefined or null reference", can you help me in this?Panto
Sure, if you post a fiddle demonstrating the error. I don't think it's related to this answer but I can't tell without seeing running code.Julee

© 2022 - 2024 — McMap. All rights reserved.