You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DC.js 序数比例尺折线图自定义排序问题求助

Fixing Custom Ordinal Order for DC.js Line Chart with BrushOn

Got it, let's get your X-axis sorted (literally!) to match your desired chronological order. The issue right now is that you're using a linear scale for categorical ordinal data, which will sort your datation values lexicographically instead of your custom timeline order. Here's how to fix it step by step:

1. Define Your Custom Order First

Start by creating an array that lists your datation values in the exact order you want them to appear on the X-axis:

const customDatationOrder = ["-30/-20", "-20/-10", "-10/1", "20/30"];

Note: Double-check your data for any inconsistent formatting (like the escaped "20\/30" entry) – make sure all datation values match the strings in this array exactly.

2. Replace Linear Scale with Ordinal Scale

Instead of d3.scaleLinear(), use d3.scaleOrdinal() and set its domain to your custom order. This tells D3 exactly how to arrange your categories:

const xScale = d3.scaleOrdinal()
  .domain(customDatationOrder)
  .range([0, lineChart.width() - lineChart.margins().left - lineChart.margins().right]);

The range maps your ordinal categories to pixel positions across the chart's width.

3. Update Your Line Chart Configuration

Adjust your chart code to use the new ordinal scale, enforce the custom order for your data group, and set proper tick values:

lineChart
  .width(950)
  .height(350)
  .margins({top: 10, right: 50, bottom: 35, left: 30})
  .dimension(graphDim)
  // Map each data key to its position in the ordinal scale
  .keyAccessor(function(kv) {
    return xScale(kv.key);
  })
  .group(graphGroup)
  .x(xScale)
  .xAxisLabel("Chronologie")
  .yAxisLabel("Effectif")
  .brushOn(true)
  .renderArea(true)
  .renderHorizontalGridLines(true)
  .renderVerticalGridLines(true)
  .elasticY(true)
  // Force the group to sort data points by your custom order
  .ordering(function(d) {
    return customDatationOrder.indexOf(d.key);
  })
  // Set X-axis ticks to only show your custom ordered values
  .xAxis()
  .tickValues(customDatationOrder);

Why This Works

  • The ordinal scale's domain explicitly defines the sequence of your datation categories, overriding default lexicographical sorting.
  • The ordering function ensures your data points are plotted in the correct sequence, so the line connects them properly.
  • tickValues guarantees only your desired categories appear as X-axis ticks, no extra or out-of-order labels.

This setup will keep your brush functionality intact (aligning with the ordinal brush pattern from dc.js examples) while giving you the exact X-axis order you need.

内容的提问来源于stack exchange,提问作者Miguel Rodriguez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:43:38