antvis/G2

[Bug]: 自定义色板报错 #6612

HelloAny posted onGitHub

Describe the bug / 问题描述

按照官网文档里的方法自定义色板,控制台报错

Image

代码:

import { Chart, register } from '@antv/g2';

register('palette.deepblues', () => {
  return ['#9ed1f7', '#76bff3', '#57b3f0', '#39abee', '#07a1ec'];
});

....
 const geoView = chart.geoView().coordinate({ type: 'mercator' });

  geoView
    .geoPath()
    .data(data)
    .encode('latitude', 'latitude')
    .encode('longitude', 'longitude')
    .scale('color', {
      palette: 'deepblues',
    })

No response

Steps to Reproduce the Bug or Issue / 重现步骤

No response

Version / 版本

🆕 5.x

OS / 操作系统

  • macOS
  • Windows
  • Linux
  • Others / 其他

Browser / 浏览器

  • Chrome
  • Edge
  • Firefox
  • Safari (Limited support / 有限支持)
  • IE (Nonsupport / 不支持)
  • Others / 其他

看了下代码, https://github.com/antvis/G2/blob/v5/src/runtime/scale.ts geoPath的scale类型是sequential

function inferScaleOptions(
  type: string,
  name: string,
  values: Primitive[][],
  options: G2ScaleOptions,
  coordinates: G2CoordinateOptions[],
): G2ScaleOptions {
  switch (type) {
    case 'linear':
    case 'time':
    case 'log':
    case 'pow':
    case 'sqrt':
      return inferOptionsQ(coordinates, options);
    case 'band':
    case 'point':
      return inferOptionsC(type, name, coordinates, options);
    case 'sequential':
      return inferOptionsS(options);
    default:
      return options;
  }
}

在这里调用了inferOptionsS函数

function inferOptionsS(options) {
  const { palette = 'ylGnBu', offset } = options;
  const name = upperFirst(palette);
  const interpolator = d3ScaleChromatic[`interpolate${name}`];
  if (!interpolator) throw new Error(`Unknown palette: ${name}`);
  return {
    interpolator: offset ? (x) => interpolator(offset(x)) : interpolator,
  };
}

里面的色板引用了d3的'd3-scale-chromatic',暂不支持自定义色板。

posted by interstellarmt 2 months ago

这里感觉是一个 bug,应该调用注册得色板。

posted by hustcc 2 months ago

这里的色板是用了d3的线性插值算法,最后的颜色还是取决于range里配置的颜色,在两个颜色间平滑地过渡,计算出连续的颜色的色值,所以geoPath如果想要自定义色板,其实就是定义渐变色的开始颜色和结束颜色,具体的写法参考下面:

        .scale('color', {
          range:['#9ed1f7','red'], // 在这里配置你的开始颜色和结束颜色
          unknown: '#fff',
        })

效果如下

Image

posted by interstellarmt 2 months ago

按照这种方式解决了,感谢解答🌹

posted by HelloAny 2 months ago

Fund this Issue

$0.00
Funded

Pull requests