Farrukh Rashid
Farrukh Rashid

Reputation: 172

Draw a line around a single point in the linechart

enter image description here

I am creating a linechart, with months on the x axis and values on the y axis. The issue is that when there is a single data point, there is no line drawn around it. I was able to draw a horizontal line using the annotations plugin but when the value is > 0 i dont know how to draw a line then, since it is supposed to be a curve.

export const optionsMap = () => ({
  maintainAspectRatio: false,
  responsive: true,
  legend: {
    display: false
  },
  elements: {
    topLabel: {}
  },
  layout: {
    padding: {
      top: 150,
      right: 45,
      left: 40,
      bottom: 5,
    }
  },
  plugins: {
    centerText: false,
    datalabels: false,
  },
  annotation: {
    drawTime: 'beforeDatasetsDraw',
    annotations: [
      {
        type: 'line',
        scaleID: 'y-axis-0',
        value: 0.01,
        mode: "horizontal",
        borderColor: "#347aeb",
        borderWidth: 2,
        backgroundColor: "rgba(255, 0, 0, 0.3)"

      }
    ]
  }
});

Upvotes: 1

Views: 728

Answers (1)

Farrukh Rashid
Farrukh Rashid

Reputation: 172

I have found a solution, hope this helps someone.

Basically we can add sample points around the single data point we have. I made a function which basically pads sample points in order to draw a line around it.

/**
 * 
 * The data points needed to draw a chart around 
 * a single point. 
 */

const padDataPoints = (data, padValue) => {
  for (let i = 0; i < padValue; i++) {
    data.push(0);
    data.unshift(0);
  }
}

This is a simple function which adds padding points on either side of the data point.

We can then make the points disappear in chart js, by making the pointRadius of all the padding points as zero.

Upvotes: 1

Related Questions