【问题标题】:Can not pass date to nivo line chart无法将日期传递给 nivo 折线图
【发布时间】:2020-08-08 02:37:30
【问题描述】:

我正在使用 nivo 折线图,并希望将 x 轴用作时间线,精确到一分钟。 不幸的是,我无法呈现该图表,因为它无法正确读取日期。例如,这是我的数据的一部分:

{ x: "2020-04-24T13:07:44.000+0000", y: 0.8063946735624102 }

这是图表获取的数据,使用以下代码生成:

let cpuEntry = {
             x: data[i].created,
             y: data[i].system_cpu
         };

当我尝试打开图表时,我收到以下错误消息:

Uncaught TypeError: v.getTime is not a function

经过一番研究,我发现图表需要一个 Date 对象。我是这样包装的:

x: new Date(data[i].created),

这给了我这样的结果:

Fri Apr 24 2020 15:07:44 GMT+0200

这个错误:

Uncaught Error: Objects are not valid as a React child (found: Fri Apr 24 2020 15:25:00 GMT+0200). If you meant to render a collection of children, use an array instead.

这是我在 ResponsiveLine 中配置的一部分:

                    xScale={{
                    format: 'native',
                    type: 'time'
                }}

我读过一些关于尝试使用“toString()”的文章,但这只是一个相同错误的圈子。我希望有一个人可以帮助我。如果需要,我会提供更多信息。

【问题讨论】:

    标签: javascript reactjs date object nivo-slider


    【解决方案1】:

    您应该将 xScale 格式指定为

    xScale={{ format: "%Y-%m-%dT%H:%M:%S.%L%Z", type: "time" }}
    

    和xFormat(作为例子)

    xFormat="time:%Y-%m-%dT%H:%M:%S.%L%Z"
    

    或者(如果你想要时间)

    xFormat="time:%H:%M:%S.%L"
    

    还可以根据您的时间间隔设置axisBottom 设置如下:

    axisBottom={{
              tickValues: "every 1 second",
              tickSize: 5,
              tickPadding: 5,
              tickRotation: 0,
              format: "%S.%L",
              legend: "Time",
              legendOffset: 36,
              legendPosition: "middle"
            }}
    

    这是一个完整的工作示例:https://codesandbox.io/s/react-hooks-counter-demo-dbr34?file=/src/index.js

    时间格式请参考https://github.com/d3/d3-time-format

    【讨论】:

    • 结合示例中的axisBottom设置,它工作得非常好。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    相关资源
    最近更新 更多