使用带刻度的相同可重复字符串值 [英] Same repeatable string values using a band scale

查看:78
本文介绍了使用带刻度的相同可重复字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是D3的新手,想绘制带有6条水平线的图表.我的xAxis是scaleLinear及其值.因此,我希望yAxis只是每个条形名称的列表.因此对于yScale,我有6个名称-['Games','Apps','Games','Apps','Games','Apps']

I'm newbie in D3 and want to draw chart with 6 horizontal bars. My xAxis is scaleLinear with their values. So I want yAxis to be just a list with each bar name. So for yScale I have 6 names - ['Games', 'Apps', 'Games', 'Apps', 'Games', 'Apps']

因此,当我使用此yScale时:

So when I use this yScale:

var params = ['Games', 'Apps', 'Games', 'Apps', 'Games', 'Apps'];
var yScale = d3.scaleBand()
 .domain(params)
 .range([0, 300])

我在yAxis上仅看到一个游戏"和一个应用" 如何列出yAxis上的所有参数而不跳过可重复的内容?

I see only one 'Games' and one 'Apps' on yAxis How to list all of the params on yAxis and not to skip repeatable?

推荐答案

您在这里看到的是任何有序刻度的默认(和预期的)行为:值必须是唯一.

What you're seeing here is the default (and expected) behaviour of any ordinal scale: the values must be unique.

如果您查看 API ,则会看到(强调我的):

If you have a look at the API, you'll see (emphasis mine):

域值内部存储在从字符串化值到索引的映射中;然后,将所得的索引用于确定频段.因此,波段标度的值必须可对字符串强制,并且域值的字符串化版本唯一标识相应的波段.

Domain values are stored internally in a map from stringified value to index; the resulting index is then used to determine the band. Thus, a band scale’s values must be coercible to a string, and the stringified version of the domain value uniquely identifies the corresponding band.

因此,任何解决方案在这里都是不可靠的.话虽如此,一个简单的解决方案是在数组的每个元素中添加无意义的 unique 值.例如,使用数组中元素的索引:

Therefore, any solution here will be a hacky one. That being said, an easy solution is adding a meaningless unique value to each element of your array. For instance, using the indices of the elements in the array:

const params = ['Games', 'Apps', 'Games', 'Apps', 'Games', 'Apps'].map(function(d, i) {
  return d + "-" + i;
});

然后我们只需使用tickFormat删除那些用于创建轴的索引:

Then we just remove those indices for creating the axis, using 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>

这篇关于使用带刻度的相同可重复字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆