dc.js x-axis will not display ticks as months, shows decimals instead

吃可爱长大的小学妹 提交于 2019-12-11 12:32:03

问题


I'm building a bar chart using dc.js, and want the x-axis to list the 12 months of the year.

So far, I have it rendering showing the first tick as a time of day (06 PM), and all subsequent ticks as decimals (thousandths).

I saw a similar question (https://stackoverflow.com/questions/21392997/dc-js-x-axis-hour-labels-appear-as-thousandths#=), but the answer involved converting milliseconds to larger units, which isn't possible with months (that I know of).

Here is my code. Thanks in advance for the help.

var parseDate = d3.time.format("%m/%d/%Y").parse;

data.forEach(function(d) {
    d.date = parseDate(d.weekStart);
    d.month = d.date.getMonth();
});

var monthDim = ndx.dimension(function(d) {return d.month;});
var milesByMonth = monthDim.group().reduceSum(dc.pluck('miles'));
//set range for x-axis
var minDate = dateDim.bottom(1)[0].date;
var maxDate = dateDim.top(1)[0].date;

var barChart  = dc.barChart("#myBarChart"); 
barChart
    .width(800).height(200)
    .margins({top: 10, right: 10, bottom: 20, left: 60})
    .dimension(monthDim)
    .group(milesByMonth)
    .gap(40)
    .transitionDuration(1500)
    .yAxisLabel('Miles Per Month')
    .renderHorizontalGridLines(true)
    .x(d3.time.scale().domain([minDate,maxDate]))
    //.x(d3.scale.ordinal())
    //.xUnits(dc.units.ordinal)
    //.x(d3.time.scale().domain([new Date(2012, 0, 1), new Date(2012, 11, 31)]))
    //.round(d3.time.month.round)
    .elasticX(true)
    .elasticY(true);

回答1:


You are using the month number for your dimension key, but dates for your x domain. I would suggest always using dates as your dimension key, but using months as your group key, so that it bins by month but doesn't lose the rest of the information.

var milesByMonth = dateDim.group(function(d) {return d.month;}).reduceSum(dc.pluck('miles'));
barChart.dimension(dateDim)

You should be able to use the axis .tickFormat() with d3.time.format to get the months printing.

Something like

var xAxis = chart.xAxis().tickFormat(d3.time. format('%B');

https://github.com/mbostock/d3/wiki/SVG-Axes#tickFormat

https://github.com/mbostock/d3/wiki/Time-Formatting

You may also need to specify

chart.xUnits(d3.time.months)


来源:https://stackoverflow.com/questions/29640111/dc-js-x-axis-will-not-display-ticks-as-months-shows-decimals-instead

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!