Open In App

How to Draw a Vertical Line at a Particular Point on the X-Axis Using Chart.js ?

Last Updated : 16 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Chart.js stands out as a versatile JavaScript library for crafting dynamic charts within web applications. One often sought-after customization is the ability to draw a vertical line at a specific point on the x-axis. This feature proves invaluable for emphasizing critical data points or marking significant events on a chart.

To draw a vertical line at a particular point on the x-axis using Chart.js, we have different approaches:

Approach 1: Using afterDraw Plugin

  • Library Inclusion: Chart.js library is included using a CDN link in the <head> section.
  • HTML Structure: HTML includes a canvas element within a div for chart rendering.
  • Chart Configuration: JavaScript configures a line chart with specified data, appearance, and scaling options.
  • Vertical Line Plugin: A custom plugin is added to draw a vertical line at x-axis value 4 after the chart is drawn.
  • Line Styling: The drawn line is styled with a red color and a 2-pixel width.
  • Chart Rendering: The chart is instantiated using the configured settings, resulting in a line chart with a highlighted vertical line at x-axis value 4.

Example: The example showcases a line chart representing a dataset of values over the months. A custom plugin is introduced using the afterDraw hook to draw a vertical line at the x-axis value of 4, emphasizing a particular data point. You can set the xValue in “ctx.moveTo(xValue, 0);” and “ctx.lineTo(xValue, chart.height);”, to align the line accordingly. The line is styled with a red color (‘rgb(255, 99, 132)’) and a 2-pixel width. The chart looks better because there’s now a clear line at a certain point on the horizontal axis. This helps draw attention to a specific data point and makes it stand out more.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Chart.js Vertical Line Example</title>
 
    <script src=
    </script>
</head>
 
<body>
    <div style="width: 80%; margin: auto;">
 
        <canvas id="myChart"></canvas>
    </div>
 
    <script>
 
        const config = {
            type: 'line',
            data: {
                labels: ['January',
                         'February',
                         'March',
                         'April',
                         'May',
                         'June',
                         'July'],
                datasets: [{
                    label: 'My First Dataset',
                    data: [65, 59, 80, 81, 56, 55, 40],
                    fill: false,
                    borderColor: 'rgb(75, 192, 192)',
                    tension: 0.1
                }]
            },
            options: {
                scales: {
                    x: {
                        beginAtZero: true,
                        grid: {
                            display: false
                        }
                    },
                    y: {
                        beginAtZero: true
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    }
                }
            },
            plugins: [{
                afterDraw: function (chart) {
                    const ctx = chart.ctx;
                    const xAxis = chart.scales.x;
 
                    // Draw vertical line at x-axis value 4
                    const xValue = xAxis.getPixelForValue(4);
                    ctx.save();
                    ctx.strokeStyle = 'rgb(255, 99, 132)';
                    ctx.lineWidth = 2;
                    ctx.beginPath();
                    ctx.moveTo(xValue, 0);
                    ctx.lineTo(xValue, chart.height);
                    ctx.stroke();
                    ctx.restore();
                }
            }]
        };
 
 
        const ctx = document.getElementById('myChart').getContext('2d');
        new Chart(ctx, config);
    </script>
</body>
 
</html>


Output:

Screenshot-(54)

Appraoch 2: Using Annotation Plugin

Cdn link:

<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation"></script>
  • Include Chart.js and Chart.js Annotation Plugin: These script tags include the Chart.js library and the Chart.js Annotation Plugin from a CDN (Content Delivery Network).
  • HTML Structure: A div element with a canvas is created. This is where the Chart.js chart will be rendered.
  • JavaScript: Sample data is defined for the chart with labels representing months and a dataset of numerical values.
  • Chart Configuration: Chart configuration options are set, including the type of scales for x and y axes, and the Annotation Plugin is used to draw a red vertical line at the x-axis value of “March.”
  • Get Chart Canvas and Create the Chart: The script gets the canvas element by its ID (myChart) and creates a new Chart.js chart with the specified data and options.

Example: In this example, we’re using the Annotation Plugin to draw a vertical line at the x-axis value corresponding to “March” in the sample data. You can customize the position and appearance of the line by modifying the annotations object within the “plugins.annotation” section in the options.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Chart.js Vertical Line with Annotation Plugin
      </title>
      </script>
    <script src=
      </script>
</head>
 
<body>
    <div style="width:80%;">
        <canvas id="myChart"></canvas>
    </div>
 
    <script>
 
        let data = {
            labels: [ "January",
                      "February",
                      "March",
                      "April",
                      "May",
                      "June",
                      "July"],
            datasets: [{
                label: "Sample Data",
                data: [12, 19, 3, 5, 2, 3, 8],
                borderColor: 'rgba(75, 192, 192, 1)',
                borderWidth: 1,
                fill: false
            }]
        };
 
        let options = {
            responsive: true,
            scales: {
                x: {
                    type: 'category',
                    position: 'bottom'
                },
                y: {
                    type: 'linear',
                    position: 'left'
                }
            },
            plugins: {
                annotation: {
                    annotations: [{
                        type: 'line',
                        mode: 'vertical',
                        scaleID: 'x',
                        value: 'March',
                        borderColor: 'red',
                        borderWidth: 2,
                        label: {
                            enabled: true,
                            content: 'Vertical Line'
                        }
                    }]
                }
            }
        };
 
 
        let ctx = document.getElementById('myChart').getContext('2d');
 
 
        let myChart = new Chart(ctx, {
            type: 'line',
            data: data,
            options: options
        });
    </script>
</body>
 
</html>


Output:

Screenshot-(3)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads