multi-measure-line-chart.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { Datum } from '@antv/ava';
  2. import { hasSubset } from '../advisor/utils';
  3. import type { ChartKnowledge, CustomChart, GetChartConfigProps, Specification } from '../types';
  4. import { findNominalField, findOrdinalField, getLineSize, processDateEncode, sortData } from './util';
  5. const MULTI_MEASURE_LINE_CHART = 'multi_measure_line_chart';
  6. const getChartSpec = (data: GetChartConfigProps['data'], dataProps: GetChartConfigProps['dataProps']) => {
  7. try {
  8. // 优先确认 x 轴,如果没有枚举类型字段,取第一个字段为 x 轴
  9. const field4Nominal = findNominalField(dataProps) ?? findOrdinalField(dataProps) ?? dataProps[0];
  10. const field4Y = dataProps?.filter(
  11. field => field.name !== field4Nominal?.name && hasSubset(field.levelOfMeasurements, ['Interval']),
  12. );
  13. if (!field4Nominal || !field4Y) return null;
  14. const spec: Specification = {
  15. type: 'view',
  16. data: sortData({ data, chartType: MULTI_MEASURE_LINE_CHART, xField: field4Nominal }),
  17. children: [],
  18. };
  19. field4Y?.forEach(field => {
  20. const singleLine: Specification = {
  21. type: 'line',
  22. encode: {
  23. x: processDateEncode(field4Nominal.name as string, dataProps),
  24. y: field.name,
  25. color: () => field.name,
  26. series: () => field.name,
  27. size: (datum: Datum) => getLineSize(datum, data, { field4X: field4Nominal }),
  28. },
  29. legend: {
  30. size: false,
  31. },
  32. };
  33. spec.children.push(singleLine);
  34. });
  35. return spec;
  36. } catch (err) {
  37. console.log(err);
  38. return null;
  39. }
  40. };
  41. const ckb: ChartKnowledge = {
  42. id: MULTI_MEASURE_LINE_CHART,
  43. name: 'multi_measure_line_chart',
  44. alias: ['multi_measure_line_chart'],
  45. family: ['LineCharts'],
  46. def: 'multi_measure_line_chart uses lines with segments to show changes in data in a ordinal dimension',
  47. purpose: ['Comparison', 'Distribution'],
  48. coord: ['Cartesian2D'],
  49. category: ['Statistic'],
  50. shape: ['Lines'],
  51. dataPres: [
  52. { minQty: 1, maxQty: '*', fieldConditions: ['Interval'] },
  53. { minQty: 1, maxQty: 1, fieldConditions: ['Nominal'] },
  54. ],
  55. channel: ['Color', 'Direction', 'Position'],
  56. recRate: 'Recommended',
  57. toSpec: getChartSpec,
  58. };
  59. /* 订制一个图表需要的所有参数 */
  60. export const multi_measure_line_chart: CustomChart = {
  61. /* 图表唯一 Id */
  62. chartType: 'multi_measure_line_chart',
  63. /* 图表知识 */
  64. chartKnowledge: ckb as ChartKnowledge,
  65. /** 图表中文名 */
  66. chineseName: '折线图',
  67. };
  68. export default multi_measure_line_chart;