我试图根据来自我的数据对象的键值在y轴上创建刻度标签。数据对象如下:
数据对象:
var data = [
{name: 'E2E Tests', passed: 4, notRun: 4, failed: 0, blocked: 0, notApplicable: 0 },
{name: '868: Services', passed: 3, notRun: 3, failed: 1, blocked: 0, notApplicable: 0 },
{name: '869: Services', passed: 2, notRun: 1, failed: 2, blocked: 1, notApplicable: 0 },
{name: 'Bugs fixed', passed: 1, notRun: 1, failed: 0, blocked: 2, notApplicable: 0 },
{name: '870: Services', passed: 2, notRun: 0, failed: 1, blocked: 0, notApplicable: 1 },
{name: '867: Local', passed: 3, notRun: 0, failed: 1, blocked: 0, notApplicable: 0 },
{name: '866: Local', passed: 3, notRun: 1, failed: 0, blocked: 0, notApplicable: 0 }
];
完整代码:
var margin = { top: 10, right: 25, bottom: 30, left: 30 };
var width = 600 - margin.left - margin.right;
var height = 400 - margin.top - margin.bottom;
var svg = d3.select('.chart')
.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.call(responsivefy)
.append('g')
.attr('transform', `translate(${margin.left}, ${margin.top})`);
svg.append('rect')
.attr('width', width)
.attr('height', height)
.style('fill', 'lightblue')
.style('stroke', 'green') ;
// Y Axis
var yScale = d3.scaleLinear()
.domain([0, 100])
.range([height, 0]);
var yAxis = d3.axisLeft(yScale);
svg.call(yAxis);
// X Axis
var xScale = d3.scaleTime()
.domain([0, 8])
.range([0, width]);
var xAxis = d3.axisBottom(xScale)
.ticks(8)
.tickFormat(d3.format("d"));
svg.append('g')
.attr('transform', `translate(0, ${height})`)
.call(xAxis);
function responsivefy(svg) {
var container = d3.select(svg.node().parentNode);
var width = parseInt(svg.style('width'));
var height = parseInt(svg.style('height'));
var aspect = width / height;
svg.attr('viewBox', '0 0 ' + width + ' ' + height)
.attr('preserveAspectRatio', 'xMinYMid')
.call(resize);
d3.select(window).on('resize.' + container.attr('id'), resize);
function resize() {
var targetWidth = parseInt(container.style('width'));
svg.attr('width', targetWidth);
svg.attr('height', Math.round(targetWidth / aspect));
}
}
我想使用名称值作为每个tick的标签。到目前为止,我已经尝试了两种方法来实现这一点。
尝试1:
我尝试创建一个名称值的独立数组,并将其传递给我添加到y轴的tickValues方法,但是没有用:
var yLabels = data.map(d => d.name);
var yAxis = d3.axisLeft(yScale).tickValues(yLabels);
尝试2:
然后我尝试将以下更改添加到y轴:
var yAxis = d3.axisLeft(yScale)
.tickValues(data)
.tickFormat(d => d.name);
这看起来像是将文本添加到svg中,但它们都位于顶部,彼此重叠。我觉得必须有一个简单而清洁的方法来做到这一点。
答案 0 :(得分:1)
问题在于您的规模(您不会使用此线性比例):
var yScale = d3.scaleBand()
.domain(["bob","Tom","Fred"]) // this is where you specify the labels
.range([height, 0]);
由于域是在轴标签跨度上打印的,因此从该范围获得特定值。轴渲染功能使用比例域。
希望此参考有助于:https://github.com/d3/d3/blob/master/API.md#scales-d3-scale
如果您有任何问题,请随时提出。