density.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { baseGeometryChannels, basePostInference, basePreInference, tooltip1d, } from './utils';
  2. export const Density = () => {
  3. return (index, scale, value, coordinate) => {
  4. const { x: X, series: S } = value;
  5. const Yn = Object.entries(value)
  6. .filter(([key]) => key.startsWith('y'))
  7. .map(([, value]) => value);
  8. const SZn = Object.entries(value)
  9. .filter(([key]) => key.startsWith('size'))
  10. .map(([, value]) => value);
  11. // Because x and y channel is not strictly required in Line.props,
  12. // it should throw error with empty x or y channels.
  13. if (X === undefined || Yn === undefined || SZn === undefined) {
  14. throw new Error('Missing encode for x or y or size channel.');
  15. }
  16. // Calc width for each box.
  17. // The scales for x and series channels must be band scale.
  18. const xScale = scale.x;
  19. const series = scale.series;
  20. const P = Array.from(index, (i) => {
  21. const groupWidth = xScale.getBandWidth(xScale.invert(+X[i]));
  22. const ratio = series ? series.getBandWidth(series.invert(+(S === null || S === void 0 ? void 0 : S[i]))) : 1;
  23. const width = groupWidth * ratio;
  24. const offset = (+(S === null || S === void 0 ? void 0 : S[i]) || 0) * groupWidth;
  25. const x = +X[i] + offset + width / 2;
  26. const PN = [
  27. ...Yn.map((_, idx) => [x + +SZn[idx][i] / index.length, +Yn[idx][i]]),
  28. ...Yn.map((_, idx) => [
  29. x - +SZn[idx][i] / index.length,
  30. +Yn[idx][i],
  31. ]).reverse(), // left
  32. ];
  33. return PN.map((p) => coordinate.map(p));
  34. });
  35. return [index, P];
  36. };
  37. };
  38. const shapes = ['density'];
  39. Density.props = {
  40. defaultShape: 'density',
  41. defaultLabelShape: 'label',
  42. composite: false,
  43. channels: [
  44. ...baseGeometryChannels({ shapes }),
  45. { name: 'x', scale: 'band', required: true },
  46. { name: 'y', required: true },
  47. { name: 'size', required: true },
  48. { name: 'series', scale: 'band' },
  49. { name: 'size', required: true, scale: 'identity' },
  50. ],
  51. preInference: [
  52. ...basePreInference(),
  53. { type: 'maybeZeroY1' },
  54. { type: 'maybeZeroX' },
  55. ],
  56. postInference: [...basePostInference(), ...tooltip1d()],
  57. interaction: {
  58. shareTooltip: true,
  59. },
  60. };
  61. //# sourceMappingURL=density.js.map