首页 > 解决方案 > React-Vega - 警告字段“x”的无限范围:[Infinity,-Infinity]

问题描述

该代码在 vega 在线编辑器中完美运行。但是在 react 组件中使用时控制台中会出现警告,并且 X 轴未在输出中呈现。

import React from 'react';
import { Vega } from 'react-vega';
import { VisualizationSpec } from 'vega-embed';

export function LineGraph() {
  const specs: VisualizationSpec = {
    $schema: 'https://vega.github.io/schema/vega/v5.json',
    description: 'A basic line chart example.',
    width: 500,
    height: 200,
    padding: 5,

    signals: [],

    data: [
      {
        name: 'table',
        format: {
          parse: { x: 'date' },
        },
      },
    ],

    scales: [
      {
        name: 'x',
        type: 'time',
        range: 'width',
        domain: { data: 'table', field: 'x' },
      },
      {
        name: 'y',
        type: 'linear',
        range: 'height',
        nice: true,
        zero: true,
        domain: { data: 'table', field: 'y' },
      },
    ],

    axes: [
      { orient: 'bottom', scale: 'x' },
      { orient: 'left', scale: 'y' },
    ],

    marks: [
      {
        type: 'line',
        from: { data: 'table' },
        encode: {
          enter: {
            x: { scale: 'x', field: 'x' },
            y: { scale: 'y', field: 'y' },
            stroke: { value: 'red' },
            strokeWidth: { value: 2 },
          },
        },
      },
    ],
  };

  const data: any = {
    table: [
      { x: '01-08-2020', y: 28, c: 0 },
      { x: '01-03-2020', y: 43, c: 0 },
      { x: '01-01-2020', y: 81, c: 0 },
      { x: '01-09-2020', y: 19, c: 0 },
      { x: '01-02-2020', y: 52, c: 0 },
      { x: '01-04-2020', y: 24, c: 0 },
      { x: '01-07-2020', y: 87, c: 0 },
      { x: '01-07-2020', y: 17, c: 0 },
      { x: '01-08-2020', y: 68, c: 0 },
      { x: '01-09-2020', y: 49, c: 0 },
    ],
  };

  const signalListeners = {};
  return (
    <div>
      <Vega data={data} signalListeners={signalListeners} spec={specs} />
    </div>
  );
}


警告:

警告字段“y”的无限范围:[Infinity,-Infinity]

警告字段“x”的无限范围:[Infinity,-Infinity]

如何在 vega 中定义范围?

标签: reactjsd3.jsvega

解决方案


此错误有两个部分 - 控制台警告和缺少渲染。

当数据尚未注入规范时,控制台警告会在摘要周期中抛出;不理想,但可以忽略AFAIK。

渲染看起来是由于react-vega处理日期解析的方式出错。与其date作为字符串传入,不如先将它们转换为Date objects,然后将修改后的数据传入Vega组件。


推荐阅读