Search code examples
node.jschart.jsreact-chartjsreact-chartjs-2

How to draw multiple line on y axis for same x axis in chartjs v2?


I have time series data in a database that looks like this:

[
  {
    min: 100,
    max: 200,
    avg: 150,
    time: 12345678.. (unix timestamp)
  },
  {
    min: ..
    ...
  }, ...
]

I am able to draw a line chart using the avg value by pulling it from the database as data points such as:

[
  {
    t: 12345678... (unix timestamp)
    y: 150 (avg value)
  },...
]

What I am trying to achieve is drawing three lines for min, max and avg respectively with the same dataset as:

[
  {
    t: 12345678... (unix timestamp),
    y1: 150 (avg value),
    y2: 100 (min value),
    y3: 200 (max value)
  },...
]

I have tried looking at documentation and many questions here but did not find a lead. I can separate the datasets but normally I am processing a lot of data on the backend and wanted to see if this can be done without any further processing. Want to know if this is achievable or it's chart.js' limitation?


Solution

  • You can't use multiple key values with Chart.JS because it is not meant to accept that data format however you can format incoming data to create a chart based on the two-line sample.

    Here is the working demo: https://jsfiddle.net/adelriosantiago/esn2wjxv/27/ enter image description here

    This is how data is prepared:

    1. Raw data in the wrong format is called rawData.
    2. The function getSingleProp transforms data (the second argument) so that only the property prop (the first argument) is extracted. This happens at the line:
    data.map((i) => {
        return { y: i[prop], x: i.time }
    })
    
    1. When calling Chart.JS we simply use getSingleProp("[the property we want]", rawData) as data resulting in the chart you are looking for.