无法将刻度线与d3.js对齐 [英] Unable to align ticks with d3.js

查看:139
本文介绍了无法将刻度线与d3.js对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用d3.js处理一个条形图,我无法使x轴上的刻度线与条形对齐.

Working with one bar chart with d3.js I am unable to align ticks in x axis with bars.

在左右两边都可以打勾,但在中间不可以. 这是代码:

In left and right verges the ticks are ok, but not in the middle. Here is the code:

var formatDate = d3.time.format("%e %b");
var height = 325;
var xTimeScale = d3.time.scale()
        .domain([new Date(data[0].date), d3.time.day.offset(new Date(data[data.length - 2].date), 1)])
        .range([30, width]);

var xAxis = d3.svg.axis()
        .scale(xTimeScale)
        .orient("bottom")
        .ticks(d3.time.days, .1)
        .tickFormat(formatDate);

chart.append("g")
        .attr("class", "xaxis axis") 
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

chart.selectAll(".xaxis text") 
        .attr("transform", function(d) {return "translate(" + this.getBBox().height * -2 + "," + this.getBBox().height + ")rotate(-45)";});

我想念什么? 预先感谢.

What am I missing? Thanks in advance.

更新:这是 jsFiddle 更新为chrtan 建议. 我现在的问题是使文本与条形图的中心对齐,而不是在左侧.

Update: Here is the jsFiddle updated with chrtan suggestions. My problem now is to align text with the center of bar and not in left.

推荐答案

从图形的外观来看,您损失了一条条形的空间.如果所有的柱线都应与刻度线左对齐,则最后一条柱线应位于1月31日的刻度线的右侧.

From the looks of your graph, you lost a bar's worth of space. If all the bars are supposed to be left-aligned against a tick, that final bar you have should be to the right of the January 31st tick.

您可能需要通过在xTimeScale的domain()中将[data.length-2]更改为[data.length-1],来添加2月1日的刻度.

You might need to add the February 1st tick by perhaps changing the [data.length - 2] to [data.length - 1] in the domain() for your xTimeScale.

然后出于显示目的,您可以使用以下命令删除最后一个刻度轴文本:

Then for display purposes, you could probably remove the last tick axis text with:

d3.select(chart.selectAll(".xaxis text")[0].pop()).remove();

内部的selectAll应该获取包含xAxis刻度文本的数组,然后弹出最后一个刻度.然后应通过外部选择器删除最后一个刻度.

The inner selectAll should get the array containing your xAxis tick texts and then pop the very last tick. This last tick should then be removed by the outer select.

这篇关于无法将刻度线与d3.js对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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