带序数数据的直方图

Histogram with ordinal data

我有带颜色的数据集,我想显示当前数据集中每种颜色的条目数。

格式化我的数据集后,它是一个字符串数组:

const colors = [
    'red',
    'green',
    'blue',
    'red',
    'red',
    'green'
]

我想制作一个可以输入直方图布局的比例尺。比例尺应有助于布局以创建多个垃圾箱。在我将数据输入直方图生成器后,我希望得到一个包含 5 个条目的数组。数组中的每个对象都应该有 x0x1 属性.

这是我阅读文档后所期望的。顺便说一句,这是我期望的最终结果:

我的代码是这样的:

const width = container.node().getBoundingClientRect().width
const xScale = d3.scaleOrdinal().domain(colors).range([0, width])
const histogramGenerator = d3.histogram()

histogramGenerator
  .domain(xScale.domain())
  .tresholds(xScale.domain().length)

const histogramData = histogramGenerator(colors)

实际结果看起来:

[Array(0)]
  0: [x0: "red", x1: "blue"]
  length: 1
  __proto__: Array(0)

我不想使用条形图,这个实验的全部目的是学习如何使用 d3 直方图和像这个颜色数据集这样的序数数据。

不幸的是,根据定义,"histogram with ordinal data" 是不可能的。您想要的是 条形图 。引用关于直方图的Wikipedia article

A histogram is an accurate representation of the distribution of numerical data. It is an estimate of the probability distribution of a continuous variable and was first introduced by Karl Pearson.

强调连续变量是我的。

如果您查看 d3.histogram source code(现已重命名为 d3.bin),您会看到它需要数值:

// Assign data to bins by value, ignoring any outside the domain.
for (i = 0; i < n; ++i) {
  x = values[i];
  if (x0 <= x && x <= x1) {
    bins[bisect(tz, x, 0, m)].push(data[i]);
  }
}

具体看x0 <= x && x <= x1

我看到你写了"I don't want to use bar chart, the whole reason of this experiment is to learn how to use d3 histogram"。在那种情况下,选择正确的数据,即具有连续变量的数据集。

条形图的解决方案:

综上所述,放弃直方图生成器并创建一个很好的旧条形图。为此,您只需要处理游览数据即可。例如,让我们使用 Array.prototype.reduce 创建对象数组,其中 colourcount.

假设这个数据数组:

const colors = ['red', 'green', 'blue', 'red', 'red', 'green', 'yellow', 'pink', 'red', 'green', 'yellow', 'pink', 'pink', 'green', 'blue', 'green', 'blue', 'green', 'green', 'green', 'green'];

我们可以这样操作:

const colors = [
  'red',
  'green',
  'blue',
  'red',
  'red',
  'green',
  'yellow',
  'pink',
  'red',
  'green',
  'yellow',
  'pink',
  'pink',
  'green',
  'blue',
  'green',
  'blue',
  'green',
  'green',
  'green',
  'green'
];

const data = colors.reduce((acc, curr) => {
  const foundObject = acc.find(e => e.colour === curr);
  if (foundObject) ++foundObject.count;
  else acc.push({
    colour: curr,
    count: 1
  });
  return acc;
}, []);

console.log(data)

现在您可以使用此数据数组创建条形图,colours 作为 x 轴中的分类变量,count 作为 y轴.