dc.js x轴不会将刻度显示为月,而是显示小数 [英] dc.js x-axis will not display ticks as months, shows decimals instead

查看:75
本文介绍了dc.js x轴不会将刻度显示为月,而是显示小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用dc.js构建条形图,并希望x轴列出一年中的12个月。

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

到目前为止,我有它将第一个刻度显示为一天中的某个时间(下午6点),随后的所有刻度显示为小数(千位)。

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

我看到了类似的问题( https://stackoverflow.com/questions/21392997/dc -js-x-axis-hour-labels-appear-as-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);


推荐答案

您正在使用月份号作为维度键,但是您的x域的日期。我建议始终使用日期作为维键,而使用月作为组键,以便它按月合并,但不会丢失其余信息。

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)

您应该可以使用轴 .tickFormat() d3.time.format 以获取打印月份。

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

类似的东西

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

您可能还需要指定

chart.xUnits(d3.time.months)

这篇关于dc.js x轴不会将刻度显示为月,而是显示小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆