Search code examples
reactjschart.jsreact-chartjs

ChartJS not rendering lines according to x-axis data


Data:

const data={
  "labels": [
    0,  
    400,
      800,
      1200,
      1600,
      2000,
      2400,
      2800,
      3200,
      3600,
      4000
  ],
  "datasets": [
    {
      "axis": 'x',
      "label": "FFF",
      "borderColor": "Red",
      "backgroundColor": "Red",
      "data": [
          {
              "x": 2883,
              "y": 129
          },
          {
              "x": 3509,
              "y": 118
          },
          {
              "x": 3916,
              "y": 73
          }
      ]
  }
  ]
};

Chart: enter image description here

I am providing both x & y axis values, the result should be like this for red line. But for current config it rendering the line from start instead of specific point on x-axis. enter image description here


Solution

  • You have to use scatter chart and showline : true option instead of line chart for this result.

    //your code
    
    const data={
      "labels": [
        0,  
        400,
          800,
          1200,
          1600,
          2000,
          2400,
          2800,
          3200,
          3600,
          4000
      ],
      "datasets": [
        {
          "axis": 'x',
          "label": "FFF",
          "borderColor": "Red",
          "backgroundColor": "Red",
          "showLine": true,         //add this option to connect dots of scatterred points
          "data": [
              {
                  "x": 2883,
                  "y": 129
              },
              {
                  "x": 3509,
                  "y": 118
              },
              {
                  "x": 3916,
                  "y": 73
              }
          ]
      }
      ]
    };
    
    <Scatter data={data} />