-->

Customize dc.js date x-axis

2019-07-27 19:44发布

问题:

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.

回答1:

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);


标签: d3.js dc.js