antvis/G2

feat: dodgeX support different sort methods for different fields of the x-axis #4191

pepper-nice posted onGitHub

背景

<img width="500" alt="image" src="https://user-images.githubusercontent.com/109653633/194706570-13d1ebe8-dcd0-4639-95a0-2d3e8827ee1e.png"> G2 4.0 的组内排序无法支持不同 x 轴字段使用不同的排序方式。这一需求在复杂数据分析场景十分需要。

API 设计

{
  type: 'interval',
  data: [
    { year: '2014', type: 'Sales', sales: 1000 },
    { year: '2015', type: 'Sales', sales: 1170 },
    { year: '2016', type: 'Sales', sales: 660 },
    { year: '2017', type: 'Sales', sales: 1030 },
    { year: '2014', type: 'Expenses', sales: 400 },
    { year: '2015', type: 'Expenses', sales: 460 },
    { year: '2016', type: 'Expenses', sales: 1120 },
    { year: '2017', type: 'Expenses', sales: 540 },
    { year: '2014', type: 'Profit', sales: 300 },
    { year: '2015', type: 'Profit', sales: 300 },
    { year: '2016', type: 'Profit', sales: 300 },
    { year: '2017', type: 'Profit', sales: 350 },
  ],
  transform: [
    {
      type: 'dodgeX',
      orderBy: {
        2014: 'ascend',
        2015: 'descend',
        2016: ['Sales', 'Profit', 'Expenses'],
      },
    },
  ],
  encode: {
    x: 'year',
    y: 'sales',
    color: 'type',
  },
};

实现方法

export function normalizeComparator(order: Order): IndexComparatorFactory {
  if(typeof order === 'object') return createCustomOrder(order);
  // ......
  return () => null;
}

// fields 获取x、y、color 的字段名称
function createCustomOrder(order, fields) {
    const xField = fields.x;
    return (data, Y, S) => {
      return ascendingComparator((i) => {
        const x = data[xField];
        if(order[x]) {
          // todo
        }
      });
    };
}

这里有几点建议:

  • reverse 也变成一个 object,不使用 ascend 和 descend 这样的关键字。
  • 暂时不支持直接写字段值,上面的写法其实不知道改值对应的字段:并不知道 Sales,Profit 和 Expenses 对应 type 字段。可以通过自定回掉的方式来实现。
  • 如果 dodgeX 支持新的排序方式,那么 stackY 也需要一起更新。
  • 可能需要使用 Map 去存储每一组的 comparator 和 reverse。
const o = {
  type: 'dodgeX',
  orderBy: {
    2014: 'ascend',
    2015: 'descend',
    2016: (d) => ['Sales', 'Profit', 'Expenses'].indexOf(d.type),
  },
  reverse: {
    2014: true,
    2015: false,
  },
};
posted by pearmini over 2 years ago

Fund this Issue

$0.00
Funded

Pull requests