d3.js - xAxis 刻度的 D3 组标签

标签 d3.js axis-labels

我有一个类似的数据集:

[
  {
    date: '2019-01-01',
    value: 100,
    group: 1
  },
  {
    date: '2019-01-02',
    value: 200,
    group: 1
  },
  {
    date: '2019-01-03',
    value: 200,
    group: 2
  },
  {
    date: '2019-01-04',
    value: 200,
    group: 3
  },
  {
    date: '2019-01-05',
    value: 100,
    group: 3
  },
  {
    date: '2019-01-06',
    value: 250,
    group: 3
  }
]

我用 yAxis - value 和 xAxis - date 创建了一个线性图表。

如何通过 group 字段值为 xAxis 实现附加标签,就像我在图片上显示的那样?

enter image description here

最佳答案

这个问题可能对您有帮助:grouped category bar chart with different groups in d3?

但是如果您只需要显示标签而不是按组显示颜色,那么您真正需要做的就是计算每个组中值的数量:

// first, group the data
var groupedData = d3.nest()
        .key(function(d) { return d.group; })
        .rollup(function(v) { return v.length; })
        .entries(data)

// then, get cumulative length of each group
var groupedData = groupedData.map((d, i) => {
        const prev = nestedData[(i - 1)]
        const cumsum = prev ? d.value + prev.cumsum : d.value
        d.cumsum = cumsum
        return d
      })

此代码将数据转换成如下形式:

    [
         {
            "key": 1,
            "values": 2,
            "cumsum": 2
         },
         {
            "key": 2,
            "values": 1,
            "cumsum": 3
         },
         {
            "key": 3,
            "values": 3,
            "cumsum": 6
         }
      ]

现在您需要做的就是将组附加到图表标签下方

const svg = //your svg selector here

const g = svg.append("g")
    .attr("class", "group-labels")
    .attr("x", 0)
    .attr("y", height + 30) //adjust this so that the group labels are below your labels

g.selectAll(".group-label")
    .data(groupedData)
    .enter()
    .append("text")
    .attr("class", "group-label")
    .attr("x", function(d, i) { return xScale.bandwidth() * d.cumsum - xScale.bandwidth() * d.value / 2 })
    .attr("y", 0)
    .attr("text-anchor", "middle")
    .attr("dominant-baseline", "hanging")

关于d3.js - xAxis 刻度的 D3 组标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57558555/

相关文章:

python /Matplotlib : How to plot in a subplot with ticks but no tick labels?

d3.js - 如何在条形图上制作垂直角?

javascript - 如何根据值的变化修改D3js图表?

css - 如何设置我的 d3 SVG 矩形的背景类?

javascript - D3 如何从 0 以外的值开始我的 y 轴

r - ggplot2 中 y 刻度标签的良好 K/M/G 缩写

python - matplotlib 将 xticks 设置为列,将标签设置为相应的索引

python-3.x - 如何将 matplotlib 图形的 `ylabel` 拆分成行?

javascript - 修改并显示使用D3生成的表中的缩写数据

javascript - 如何用 sinon 模拟 d3.select.selectall ?