ArticleZip > Draw Horizontal Line On Chart In Chart Js On V2

Draw Horizontal Line On Chart In Chart Js On V2

Are you looking to add some flair to your Chart.js charts by drawing a horizontal line across your data points? Well, you're in luck because in this how-to guide, we'll walk you through the steps on how to draw a horizontal line in Chart.js v2.

Chart.js is a popular JavaScript library for creating visually appealing and interactive charts on web pages. Drawing a horizontal line on your chart can help highlight specific data points or provide a visual reference for comparison. Let's dive into the steps to achieve this effect.

First, make sure you have Chart.js v2 included in your project. If you haven't added it yet, you can easily do so by including the library in your HTML file or through a package manager like npm or yarn.

Next, let's create a new horizontal line by defining a plugin for the Chart.js instance. Here's an example code snippet to help you get started:

Javascript

Chart.plugins.register({
  afterDraw: function(chart) {
    if (chart.tooltip._active && chart.tooltip._active.length) {
      const activePoint = chart.tooltip._active[0];
      const ctx = chart.ctx;
      const x = activePoint.tooltipPosition().x;
      const topY = chart.scales['y-axis-0'].top;
      const bottomY = chart.scales['y-axis-0'].bottom;

      // Draw horizontal line
      ctx.save();
      ctx.beginPath();
      ctx.moveTo(x, topY);
      ctx.lineTo(x, bottomY);
      ctx.lineWidth = 2;
      ctx.strokeStyle = '#FF0000'; // Set color here
      ctx.stroke();
      ctx.restore();
    }
  }
});

In this code snippet, we are creating a new Chart.js plugin that listens for the `afterDraw` event. When the chart's tooltip is active, we retrieve the x position of the active point and draw a horizontal line spanning the y-axis.

You can customize the appearance of the line by adjusting the `ctx.lineWidth` for the line thickness and `ctx.strokeStyle` for the line color. Feel free to experiment with different colors and styles to match your chart's design.

Finally, don't forget to include this plugin in your Chart.js configuration:

Javascript

plugins: [{
  afterDraw: function(chart) {
    // Plugin logic here
  }
}]

By adding this plugin to your Chart.js configuration, you can easily draw horizontal lines on your charts to enhance the visualization of your data.

In conclusion, drawing a horizontal line on a Chart.js chart in v2 is a simple yet effective way to convey additional information or emphasize specific data points. With the right plugin and configuration, you can easily customize the appearance of the line to suit your design needs. Experiment with different styles and colors to create visually compelling charts that capture your audience's attention.