在一个类似于水平条形图的图表中,我想在每一行中显示多个条形图/方框,它们之间有空格。例如,我想在第0行显示三个框,以说明以下数据:
+--+ +-+ +---+
row-0: 3-5, 7-8, 9-11 -> +--+ +-+ +---+
+-+ +----+
row-1: 1-2, 5-9 -> +-+ +----+
+-+ +--+
row-2: 4-5, 8-10 -> +-+ +--+
使用d3.js v5
发布于 2020-07-29 16:51:28
我将您的问题解释为有间隙的水平条形图,因此它们都具有相同的高度(因此与直方图不同)。我想这应该足以让你上路了。钢筋高度是动态的,基于钢筋组的数量,并且每个钢筋组都有一个钢筋段阵列。
const barGroups = [
[{ min: 0, max: 10 }, { min: 12, max: 15 }],
[{ min: 10, max: 14 }],
[{ min: 4, max: 6 }, { min: 8, max: 11 }],
[{ min: 0, max: 8 }]
];
const margin = {
left: 10,
right: 10,
top: 10,
bottom: 40
};
padding = 2;
const width = 500, height = 150;
const barHeight = height / barGroups.length;
console.log(height, barHeight);
const svg = d3.select("svg")
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom);
const x = d3.scaleLinear()
.rangeRound([0, width]);
const colors = ['darkred', 'darkgreen', 'darkblue'];
// The last value is the highest
x.domain([0, d3.max(barGroups.map((g) => g[g.length - 1].max))]);
svg.append("g")
.attr("transform", "translate(" + margin.left + "," + (height + margin.top) + ")")
.call(d3.axisBottom(x))
const groupElements = svg.selectAll('.group')
.data(barGroups)
.enter()
.append('g')
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.classed('group', true);
groupElements.each(function(_, i) {
d3.select(this)
.selectAll(".bar")
.data((d) => d)
.enter()
.append("rect")
.classed("bar", true)
.attr("x", (d) => x(d.min))
.attr("width", (d) => x(d.max - d.min))
.attr("y", i * barHeight + padding)
.attr("height", barHeight - 2 * padding)
.attr("fill", colors[i % colors.length]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.js"></script>
<svg></svg>
https://stackoverflow.com/questions/63147251
复制相似问题