我是 D3 的新手,想绘制带有 6 个水平条的图表。我的 xAxis 与它们的值是scaleLinear 的。所以我希望 yAxis 只是一个包含每个条形名称的列表。所以对于 yScale 我有 6 个名称 - ['Games', 'Apps', 'Games', 'Apps', 'Games', 'Apps']
所以当我使用这个 yScale 时:
var params = ['Games', 'Apps', 'Games', 'Apps', 'Games', 'Apps'];
var yScale = d3.scaleBand()
.domain(params)
.range([0, 300])
I see only one 'Games' and one 'Apps' on yAxis
How to list all of the params on yAxis and not to skip repeatable?
您在这里看到的是任何序数比例的默认(和预期)行为:值必须是unique.
如果你看一下API https://github.com/d3/d3-scale#band_domain,你会看到(强调我的):
域值内部存储在从字符串化值到索引的映射中;然后使用所得索引来确定频带。因此,带标度的值必须可强制转换为字符串,并且域值的字符串化版本uniquely识别相应的频段。
所以,任何解决方案这将是一个 hacky 的问题。话虽这么说,一个简单的解决方案是添加一个无意义的unique数组中每个元素的值。例如,使用数组中元素的索引:
const params = ['Games', 'Apps', 'Games', 'Apps', 'Games', 'Apps'].map(function(d, i) {
return d + "-" + i;
});
然后我们只需删除那些用于创建轴的索引,使用tickFormat
:
const yAxis = d3.axisLeft(yScale)
.tickFormat(function(d) {
return d.split("-")[0];
});
这是一个演示:
const svg = d3.select("svg");
const params = ['Games', 'Apps', 'Games', 'Apps', 'Games', 'Apps'].map(function(d,i) {
return d + "-" + i;
});
const yScale = d3.scaleBand()
.domain(params)
.range([2, 148]);
const yAxis = d3.axisLeft(yScale)
.tickFormat(function(d) {
return d.split("-")[0];
});
yAxis(svg.append("g").attr("transform", "translate(100,0)"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg></svg>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)