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"));
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.
Fork of your fiddle.
Related
I am using a crossfilter2 with dcv3
My data is in a csv which i loaded into memory
Original Data
Day, ID
1, 2
1, 2
1, 2
2, 5
3, 6
4, 6
Processed data
Day, ID, target
1, 2, True
1, 2, True
1, 2, True
2, 5, False
3, 6, False
4, 6, False
Currently what i am trying to do is create a crossfilter stackedbar chart with 2 bars. If ID == 2, i consider it as one group, and ID !=2 as another group. However, i cannot do it dynamically it in DC/crossfilter which results me having to preprocess the data to add a new column and work off the column as shown by my solution below.
Is there a better way?
var dimID = ndx.dimension(function(d) { return d.day; });
var id_stacked = dimID.group().reduce(
function reduceAdd(p, v) {
p[v.target] = (p[v.target] || 0) + 1;
return p;
},
function reduceRemove(p, v) {
p[v.target] = (p[v.target] || 0) - 1;
return p;
},
function reduceInitial() {
return {};
});
//Doing the stacked bar chart here
stackedBarChart.width(1500)
.height(150)
.margins({top: 10, right: 10, bottom: 50, left: 40})
.dimension(dimID)
.group(id_stacked, 'Others', sel_stack("True"))
.stack(id_stacked, 'Eeid of interest', sel_stack("False"))
This is my sel_stack function
function sel_stack(i) {
return function(d) {
return d.value[i] ? d.value[i] : 0;
};
}
I am plotting a bar chart with x-axis being the day and the Y-axis being the frequency of ID == 2 or ID!=2 in a stacked bar chart
So you want to group by day and then stack by whether ID===2. Although dc.js will accept many different formats, often the trick is getting the data into the right shape.
You're on the right track, but you don't need the extra column in order to create stacks for "is 2" and "not 2". You can calculate it directly:
var dayDimension = ndx.dimension(function(d) { return d.Day; }),
idStackGroup = dayDimension.group().reduce(
function add(p, v) {
++p[v.ID===2 ? 'is2' : 'not2'];
return p;
},
function remove(p, v) {
--p[v.ID===2 ? 'is2' : 'not2'];
return p;
},
function init() {
return {is2: 0, not2: 0};
});
These are standard add/remove functions for reducing multiple values for each bin. You'll find other variations where the name of the field is driven by the data. But here we know what fields will exist, so we can initialize them to zero in init and not worry about encountering new fields.
The add function is called when a row is added to the crossfilter or a filter changes so that a row is included; the remove function is called whenever a row is filtered out or removed from crossfilter. Since we're not worried about undefined (1) we can simply increment (++) and decrement (--) the values.
Finally we need accessors to pull these values out of the object. I think it's simpler to put the stack accessors inline - sel_stack was written for adding a dynamic number of stacks. (YMMV)
.group(idStackGroup, 'Others', d => d.value.not2)
.stack(idStackGroup, 'Eeid of interest', d => d.value.is2);
https://jsfiddle.net/gordonwoodhull/fu4w96Lh/23/
(1) If you do any arithmetic on undefined it casts to NaN and NaN ruins all further calculations.
I'm trying to create a histogram using dc.js to display post counts aggregated by month. I've set up the crossfilter dimension and group to aggregate the data correctly but I can't get the widths of the resulting chart to fill the correct widths on the x axis.
My (simplified) code looks like this:
var ndx = crossfilter(items)
var dateDimension = ndx.dimension(d => d.date)
// group by month
var overviewGroup = dateDimension.group(d => {
if (d) {
return new Date(d.getUTCFullYear(), d.getUTCMonth())
}
})
var minMonth = new Date(dateDimension.bottom(1)[0].date.getUTCFullYear(), dateDimension.bottom(1)[0].date.getUTCMonth())
var maxMonth = new Date(dateDimension.top(1)[0].date.getUTCFullYear(), dateDimension.top(1)[0].date.getUTCMonth() + 1)
this.overviewChart
.height(60)
.minWidth(600)
.width(null)
.margins({top: 0, right: 10, bottom: 30, left: 40})
.dimension(dateDimension)
.centerBar(false)
.x(scale.scaleTime().domain([minMonth, maxMonth]))
.round(time.timeMonths.round)
.xUnits(time.timeMonths)
.group(overviewGroup)
.on('filtered', () => { this.displayItems = ndx.allFiltered() })
This displays the correct data on the y axis but the bars are only 1px wide. The chart in question is the smaller, lower chart - it's supposed to be the range chart for the higher-resolution one above (which aggregates posts by day and is displaying correctly) but that's for another question!
I get better results with .xUnits(() => { return overviewGroup.all().length - 1 }) which produces a wider bar and is closer to my intended result but it's still not correct:
I've pulled my code into a fiddle however in the fiddle it works more or less as expected: https://jsfiddle.net/y1qby1xc/9/
Using bar chart:
actionsChart /* dc.barChart('#volume-month-chart', 'chartGroup') */
.width(actionsWidth)
.height(240)
.margins({top: 10, right: 50, bottom: 30, left: 40})
.dimension(dateDimension)
//...
.elasticX(true)
.elasticY(true)
.gap(1)
.alwaysUseRounding(true)
.x(d3.time.scale().domain( [ minDate, maxDate ] ) )
.round(d3.time.day.round)
.xUnits(d3.time.days)
.renderHorizontalGridLines(true)
//.xAxisLabel( 'Dan')
//.xAxisPadding(2)
.xAxisLabel( "Datum")
//.yAxisLabel( "Akcije" ) // OK, but already in title
.xAxisPadding(1)
//nok in dc: //.tickFormat(d3.time.format("%Y-%m-%d"))
//.label( function(d){ return JSON.stringify(d); })
;
It gets Label on x-axis unreadable (too much characters next to each other.
How to put label each 5 or 7 days, and customize format (day in month number, no week day) ?
Thank you.
dc.js mostly uses d3v3's d3.svg.axis to draw its axes.
You may be looking for d3.svg.axis.ticks() and d3.svg.axis.tickFormat().
You can get at the d3 axis object that dc.js uses by calling chart.xAxis() but I advise doing it in a separate statement from your other chart initialization because it gets confusing when you you chain function calls but they return different objects.
So, something like (untested):
chart.xAxis()
.ticks(d3.time.days, 7)
.tickFormat(d3.time.format('%e'));
d3v3 time formatting specifiers
If you can't get the automatic tick generator to do what you want, you can always specify the exact list of ticks using .tickValues(). You'd want to do this before each render and redraw, so (again, untested):
function calc_ticks(chart) {
var ticks = d3.time.weeks(chart.xAxisMin(), chart.xAxisMax()); // or days(chart.xAxisMin(), chart.xAxisMax(), 5)
chart.xAxis().tickValues(ticks);
}
chart.on('preRender', calc_ticks)
.on('preRedraw', calc_ticks);
I would like to create a bar chart based on dates in x-axis. Labels should be displayed as month (i.e. Jan, Jan'17 - preferred). Within my data I have always first date of following months, i.e. 01Jan, 01Feb, 01Mar. I have created a chart but I am not able to make it aligned.
var chart = dc.barChart("#" + el.id);
var chCategory = ndx.dimension(function(d) {return d[chCategoryName];});
chValues = chCategory.group().reduceSum(
return parseFloat(d[chValueName]);});
//set range for x-axis
var minDate = chCategory.bottom(1)[0][chCategoryName];
var maxDate = chCategory.top(1)[0][chCategoryName];
chart
.width(800)
.height(200)
.x(d3.time.scale().domain([minDate,maxDate]))
.xUnits(d3.time.months)
.dimension(chCategory)
.group(chValues)
.renderHorizontalGridLines(true)
// .centerBar(true) //does not look better
.controlsUseVisibility(true)
.ordinalColors(arrColors)
.transitionDuration(1000)
.margins({top: 10, left: 80, right: 5, bottom: 20})
I have already read post: dc.js x-axis will not display ticks as months, shows decimals instead
but I am not able to implement it in a way that will keep correct sorting for different years.
dc.js takes the domain pretty literally - the x axis stretches exactly from the beginning to the end, disregarding the width of the bars or their placement. It's a design bug.
Here are two workarounds.
keep bars centered and add padding
If you're using elasticX you can manually correct it like this:
chart.centerBar(true)
.xAxisPadding(15).xAxisPaddingUnit('day')
If you're just setting the domain manually, that's
minDate = d3.time.day.offset(minDate, -15);
maxDate = d3.time.day.offset(maxDate, 15);
align the ticks to the left of bars and correct the right side of the domain
You don't say what problem you run into when you don't center the bars. But I know the right bar can get clipped.
If you want the elasticX effect, you can implement it manually like this, offsetting the right side by a month (example):
function calc_domain(chart) {
var min = d3.min(chart.group().all(), function(kv) { return kv.key; }),
max = d3.max(chart.group().all(), function(kv) { return kv.key; });
max = d3.time.month.offset(max, 1);
chart.x().domain([min, max]);
}
chart.on('preRender', calc_domain);
chart.on('preRedraw', calc_domain);
Or without elasticX that's just:
maxDate = d3.time.month.offset(maxDate, 1);
My dataset is an array of json of the like :
var data = [ { company: "A", date_round_1: "21/05/2002", round_1: 5, date_round_2: "21/05/2004", round_2: 20 },
...
{ company: "Z", date_round_1: "16/01/2004", round_1: 10, date_round_2: "20/12/2006", round_2: 45 }]
and I wish to display both 'round_1' and 'round_2' time series as stacked line charts.
The base line would look like this :
var fundsChart = dc.lineChart("#fundsChart");
var ndx = crossfilter(data);
var all = ndx.groupAll();
var date_1 = ndx.dimension(function(d){
return d3.time.year(d.date_round_1);
})
fundsChart
.renderArea(true)
.renderHorizontalGridLines(true)
.width(400)
.height(360)
.dimension(date_1)
.group(date_1.group().reduceSum(function(d) { return +d.round_1 }))
.x(d3.time.scale().domain([new Date(2000, 0, 1), new Date(2015, 0, 1)]))
I have tried using the stack method to add the series but the problem resides in the fact that only a single dimension can be passed as argument of the lineChart.
Can you think of a turnaround to display both series while still using a dc chart?
Are you going to be filtering on this chart? If not, just create a different group on a date_2 dimension and use that in the stack. Should work.
If you are going to be filtering, I think you'll have to change your data model a bit. You'll want to switch to have 1 record per round, so in this case you'll have 2 records for every 1 record you have now. There should be 1 date property (the date for that round), an amount property (the contents of round_x in the current structure), and a 'round' property (which would be '1', or '2', for example).
Then you need to create a date dimension and multiple groups on that dimension. The group will have a reduceSum function that looks something like:
var round1Group = dateDim.group().reduceSum(function(d) {
return d.round === '1' ? d.amount : 0;
});
So, what happens here is that we have a group that will only aggregate values from round 1. You'll create similar groups for round 2, etc. Then stack these groups in the dc.js chart.
Hopefully that helps!