javascript d3条形图倒置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15011256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:09:40  来源:igfitidea点击:

d3 bar chart is upside down

javascriptd3.js

提问by Phil Gyford

I have a simple bar chart drawn in d3, with vertical bars: http://jsfiddle.net/philgyford/LjxaV/2/

我有一个用 d3 绘制的简单条形图,带有垂直条:http: //jsfiddle.net/philgyford/LjxaV/2/

However, it's drawing the bars down, with the baseline at the top of the chart.

但是,它正在向下绘制条形图,基线位于图表顶部。

I've read that to invert this, drawing up from the bottom, I should change the range()on the y-axis. So, change this:

我读过要反转它,从底部向上绘制,我应该更改range()y 轴上的 。所以,改变这个:

    .range([0, chart.style('height')]);

to this:

对此:

    .range([chart.style('height'), 0]);

However, that looks like it's drawing the inverse of the chart - drawing in the space aboveeach of the bars, and leaving the bars themselves (drawn from the bottom) transparent. What am I doing wrong?

但是,这看起来像是在绘制图表的倒数 - 在每个条形上方的空间中绘制,并使条形本身(从底部绘制)保持透明。我究竟做错了什么?

回答by cmonkey

Per the d3 basic bar chart : http://bl.ocks.org/mbostock/3885304

根据 d3 基本条形图:http: //bl.ocks.org/mbostock/3885304

You are correct in inverting the range.

您反转范围是正确的。

Additionally, your rectangles should be added like this:

此外,您的矩形应该像这样添加:

    .attr('y', function(d) { return y(d.percent); } )
    .attr('height', function(d,i){ return height - y(d.percent); });

回答by mike j m

Setting the y attribute seems to work:

设置 y 属性似乎有效:

.attr('y', function(d){ return (height - parseInt(y(d.percent))); })

jsfiddle here

jsfiddle在这里

回答by Jared Wilber

The x and y coordinates for svgstart in the top left. You want the y to start on the bottom. The code below assumes you're appending to some function along the lines of:

左上角svg开始的 x 和 y 坐标。您希望 y 从底部开始。下面的代码假设您要附加到一些函数中:

svg.selectAll('rect')
    .data(dataset)
    .enter()
    .append('rect')

To make the bar plot act as you desire, set the y attribute to begin at distance data[i]above the axis:

要使条形图按照您的意愿运行,请将 y 属性设置为data[i]在轴上方的距离处开始:

.attr('y', function(d) { return height - d; })

Then, you must make the distance extend the remaining data[i]to the axis.

然后,您必须使距离延伸data[i]到轴的剩余部分。

.attr('height', function(d) { return d; }) 

And that's it!

就是这样!