DC.js 序数比例尺折线图自定义排序问题求助
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
domainexplicitly defines the sequence of yourdatationcategories, overriding default lexicographical sorting. - The
orderingfunction ensures your data points are plotted in the correct sequence, so the line connects them properly. tickValuesguarantees 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

