Customize dc.js date x-axis

半世苍凉 提交于 2020-01-05 04:05:24

问题


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


来源:https://stackoverflow.com/questions/46004978/customize-dc-js-date-x-axis

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