简体   繁体   English

带序刻度的可变带大小

[英]Variable band sizes with ordinal scale

I'd like to create an ordinal axis with varying sizes of rangeRounds or bands. 我想创建一个具有变化的rangeRounds或band大小的序数轴。 Its fairly straight forward to do this using a linear axis but wondered if it where possible to do this with an ordinal axis. 使用线性轴执行此操作相当简单,但想知道是否有可能使用序数轴执行此操作。 I wondered if I use range and have explicit values, but can't seem to make that work either. 我想知道我是否使用范围并具有显式值,但似乎也无法使它正常工作。 I'm trying to create this kind of thing: 我正在尝试创建这种东西:

在此处输入图片说明

You cannot get variable bands with a band scale ( d3.scaleBand() ). 您无法获得具有波段比例( d3.scaleBand() )的可变波段。 However, getting variable intervals with a regular ordinal scale ( d3.scaleOrdinal() ) is quite trivial. 但是,获得具有规则序数标度( d3.scaleOrdinal() )的可变间隔非常简单。

For instance: 例如:

var scale = d3.scaleOrdinal()
  .domain(["Lemons", "Oranges", "Pears", "Apples", "Bananas"])
  .range([10, 40, 100, 150, 180, 290]);

The only complicated thing is moving the ticks to the center of the axis... but it's not that complicated: 唯一复杂的事情是将刻度线移动到轴的中心...但这并不那么复杂:

axisGroup.selectAll("text").each(function(d, i) {
  d3.select(this).attr("transform", "translate(0," + (scale.range()[i + 1] - scale(d)) / 2 + ")")
})

Here is a demo: 这是一个演示:

 var svg = d3.select("svg"); var scale = d3.scaleOrdinal() .domain(["Lemons", "Oranges", "Pears", "Apples", "Bananas"]) .range([10, 40, 100, 150, 180, 290]); var rects = svg.selectAll(null) .data(scale.domain()) .enter() .append("rect") .attr("x", 100) .attr("width", 200) .attr("y", function(d) { return scale(d) }) .attr("height", function(d, i) { return scale.range()[i + 1] - scale(d) }) .style("fill", "#ccc") .style("stroke", "white") .style("stroke-width", 2) var axis = d3.axisLeft(scale); var gY = svg.append("g") .attr("transform", "translate(100,0)") .call(axis); gY.selectAll("text").each(function(d, i) { d3.select(this).attr("transform", "translate(0," + (scale.range()[i + 1] - scale(d)) / 2 + ")") }) 
 <script src="https://d3js.org/d3.v4.min.js"></script> <svg height=300></svg> 

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

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