简体   繁体   English

水平条形图y轴对齐

[英]Horizontal bar chart y axis alignment

I have a problem with the yAxis in my horizontal bar chart. 我的水平条形图中的yAxis出现问题。

var data = [0, 0, 0, 4, 0, 0, 0, 0, 18, 0, 0, 0, 52, 14, 0, 16];

var margin = { left: 20, top: 0  },
    width = 420,
    barHeight = 20,
    height = barHeight * data.length;

var xScale = d3.scale.linear()
    .domain([0, d3.max(data)])
    .range([0, width - margin.left]);

var yScale = d3.scale.linear()
    .domain([0, data.length])
    .range([0, height]);

var chart = d3.select(".degree-hist")
    .attr("width", width)
    .attr("height", barHeight * data.length)
    .append("g")
    .attr("transform", function(d, i) { return "translate(" + margin.left + ", 0)"; });

var bar = chart.selectAll("g")
    .data(data)
    .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

bar.append("rect")
    .attr("width", xScale)
    .attr("height", barHeight - 1);

bar.append("text")
    .attr("x", function(d) { return xScale(d) - 3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d > 0 ? d : ""; });

var yAxis = d3.svg.axis()
    .orient('left')
    .scale(yScale)
    .tickSize(2)
    .tickFormat(function(d, i){ return i + 1; })
    .tickValues(d3.range(data.length));

chart.append('g')
    .attr("transform", "translate(0,0)")
    .attr('id','yaxis')
    .call(yAxis);

I've illustrated the problem here: http://jsfiddle.net/mt556rot/3/ 我在这里说明了这个问题: http : //jsfiddle.net/mt556rot/3/

For some reason I did not manage to align the y-axis labels. 由于某些原因,我无法对齐y轴标签。 I'd like to align the labels to the bar they belong to. 我想将标签与标签所属的栏对齐。 In my example they appear on the upper edge of the bar, though. 不过,在我的示例中,它们显示在条的上边缘。 Also the ticks are not visible. 刻度线也不可见。

Any ideas how to fix this? 任何想法如何解决这一问题?

You are not centering the bars on the axis labels, they are starting on them: 您没有将条形图居中放置在轴标签上,而是从它们开始:

bar.append("rect")
  .attr("width", xScale)
  .attr("height", barHeight - 1)
  .attr("y", -barHeight / 2); <-- added this to center

Also, your top tick label is being cut off because you didn't take into account the top margin: 另外,您的最高刻度标签被切断了,因为您没有考虑top边距:

var chart = d3.select(".degree-hist")
    .attr("width", width)
    .attr("height", barHeight * data.length + margin.top)
    .append("g")
    .attr("transform", function(d, i) { return "translate(" + margin.left + ", " + margin.top + ")"; }); // <-- margin.top into transform with top > 0

Finally, you didn't set any style for your ticks (CSS from here ): 最后,您没有为刻度线设置任何样式(来自此处的 CSS):

#yaxis path,
#yaxis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

Updated fiddle . 更新小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM