Tips on eliminating unwanted gridlines in Chart.js?

After creating a chart using Chartjs, I am facing an issue with some pixels that I want to remove. To make it clearer, here is an image demonstrating the problem:

https://i.sstatic.net/sSoK6.png

Below is the code snippet responsible for generating this particular graph:

var options = {
    type: 'bar',
    data: {
        labels: ["1", "2", "3", "4", "5"],
        datasets: [
            {
                borderWidth: 2,
                borderColor: "#5d5d5d",
                pointBorderColor: "#5d5d5d",
                pointBackgroundColor: "#5d5d5d",
                pointBorderWidth: 5,
                type: 'line',
                data: [26, 26, 33, 28, 30],
                fill: false,
                lineTension: 0
            },
            {
                borderWidth: 3,
                pointBorderColor: "#b8b8b8",
                pointBackgroundColor: "#b8b8b8",
                pointBorderWidth: 10,
                type: 'line',
                data: [26, 26, 29, 28, 29],
                fill: false,
                lineTension: 0
            },
            {
                data: [0, 0, 0, 0, 0],
                fill: false,
                lineTension: 0
            }
        ]
    },
    options: {
        hover: {mode: null},
        legend: {
            display: false
        },
        tooltips: {enabled: false},
        hover: {mode: null},
        scales: {
            xAxes: [{
                gridLines: {
                    // drawBorder: false,
                },
            }],
            yAxes: [{
                display: false,
                ticks: {
                    suggestedMin: 0,
                    max: 60,
                    beginAtZero: true
                }
            }]
        }
    }
}

var ctx = document.getElementById(elementID).getContext('2d');
new Chart(ctx, options);

Seeking advice from those familiar with Chart.js - how can I effectively eliminate those undesirable overlapping lines?

Answer №1

If you're looking to eliminate those unwanted overlapping lines on your chart, consider using this helpful chart plugin:

Chart.plugins.register({
   beforeDraw: function(chart) {
      var ctx = chart.chart.ctx,
         x_axis = chart.scales['x-axis-0'],
         topY = chart.scales['y-axis-0'].top,
         bottomY = chart.scales['y-axis-0'].bottom;
      x_axis.options.gridLines.display = false;
      x_axis.ticks.forEach(function(label, index) {
         var x = x_axis.getPixelForValue(label);
         ctx.save();
         ctx.beginPath();
         ctx.moveTo(x, topY);
         ctx.lineTo(x, bottomY);
         ctx.lineWidth = 1;
         ctx.strokeStyle = x_axis.options.gridLines.color;
         ctx.stroke();
         ctx.restore();
      });
   }
});

ᴡᴏʀᴋɪɴɢ ᴅᴇᴍᴏ ⧩

Chart.plugins.register({
   beforeDraw: function(chart) {
      var ctx = chart.chart.ctx,
         x_axis = chart.scales['x-axis-0'],
         topY = chart.scales['y-axis-0'].top,
         bottomY = chart.scales['y-axis-0'].bottom;
      x_axis.options.gridLines.display = false;
      x_axis.ticks.forEach(function(label, index) {
         var x = x_axis.getPixelForValue(label);
         ctx.save();
         ctx.beginPath();
         ctx.moveTo(x, topY);
         ctx.lineTo(x, bottomY);
         ctx.lineWidth = 1;
         ctx.strokeStyle = x_axis.options.gridLines.color;
         ctx.stroke();
         ctx.restore();
      });
   }
});

var options = {
   type: 'bar',
   data: {
      labels: ["1", "2", "3", "4", "5"],
      datasets: [{
         borderWidth: 2,
         borderColor: "#5d5d5d",
         pointBorderColor: "#5d5d5d",
         pointBackgroundColor: "#5d5d5d",
         pointBorderWidth: 5,
         type: 'line',
         data: [26, 26, 33, 28, 30],
         fill: false,
         lineTension: 0
      }, {
         borderWidth: 3,
         pointBorderColor: "#b8b8b8",
         pointBackgroundColor: "#b8b8b8",
         pointBorderWidth: 10,
         type: 'line',
         data: [26, 26, 29, 28, 29],
         fill: false,
         lineTension: 0
      }, {
         data: [0, 0, 0, 0, 0],
         fill: false,
         lineTension: 0
      }]
   },
   options: {
      hover: {
         mode: null
      },
      legend: {
         display: false
      },
      tooltips: {
         enabled: false
      },
      hover: {
         mode: null
      },
      scales: {
         xAxes: [{
            gridLines: {
               // drawBorder: false,
            },
         }],
         yAxes: [{
            display: false,
            ticks: {
               suggestedMin: 0,
               max: 60,
               beginAtZero: true
            }
         }]
      }
   }
}

var ctx = document.getElementById('canvas').getContext('2d');
new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to ensure a div takes up the rest of the height on a page when the header's size is unpredictable

Is there a way to make the red area fill the remaining visible space without overlapping into the footer? I also need the infoContent section to be scrollable. The height of the header may vary. I came across some older solutions that suggested using Java ...

The watch function in the scope is not triggered after initialization (ui-router)

Upon visiting a page, I encounter the following code: <div ng-if='$stateParams.show=="previous"'> From <input type="text" ng-model="year_from" /> <br/> To <input type="text" ng-model=" ...

The div element is shifting as the page is being resized

When I increase the zoom level of my page to 110%, the div inside the larger one keeps getting bigger and eventually moves to a new line. Is there a way to stop it from shifting? If so, please provide guidance on how to fix this issue without criticizing m ...

Creating a Full Page Background Image That Fits Perfectly Without Resizing or Cropping

Can someone help me achieve the same effect as the website linked below, where the background image fades instead of being a slideshow? The image should be 100% in width and height without any cropping. I have managed to set this up with the codes provided ...

Creating a three-tiered navigation menu using Bootstrap 4

I am struggling with adding a 3-level dropdown menu to my website. My HTML code seems correct, and I have added the necessary CSS styles, but the last dropdown menus are appearing in the wrong place. <li class="nav-item dropdown"> ...

When my screen measures 1700px wide, a width of 100% in CSS appears significantly narrower than a width of 500px

Currently, I am working on designing a responsive layout for a 3D globe. The code snippet that stores the structure is as follows: <div class="text-center main"> <canvas id='globe' width='100%' height='100%'> ...

What are the steps for creating a standalone build in nextJS?

Currently, I am undertaking a project in which nextJS was chosen as the client-side tool. However, I am interested in deploying the client as static code on another platform. Upon generating a build, a folder with all the proprietary server elements of ne ...

Ways to revert to the initial state in React.js

Check out my codeSandbox project here: https://codesandbox.io/s/bold-lederberg-d2h508?file=/src/Components/Products/Products.js I'm having trouble getting the items back to their original presentation when clicking on "default" - sorting by price wor ...

The vuex store does not activate in routed components

After setting up my vuex store and ensuring that everything is functioning properly, I encountered an issue where I can only commit mutations in components that are directly imported into src App.vue. For instance, the resetState function in Header.vue su ...

Encountering an issue with the `className` prop not matching when deploying to Heroku, yet the functionality works perfectly when testing locally

I encountered this specific error message: The className property did not match. On the server: "jss1 jss5" Client side: "makeStyles-root-1 makeStyles-root-5" This issue only arises when deploying to Heroku. Locally, everything runs ...

Eliminating single and multiple relationships - Mongoose

My Assignment schema includes references to both Groups and Projects. Assignment == Group [One-One Relationship] Assignment == Projects [One-Many Relationship] Here is my Assignment Schema: var AssignmentSchema = new Schema({ name: String, group ...

Creating tables and defining their structure with jQuery for HTML can be done using the following steps

I have retrieved values from the database in a variable by parsing it from JSON format. Now, I need to generate an HTML table structure as shown below: <table class="table dataList fiberEngg"> <tbody> <tr> <td& ...

Deactivate the attribute in the media query

I made some website with pure html/css. I defined overflow-y: scroll to some element when browser is full screen. But when screen's width is less than 400px, I want to disable that. (like, overflow-y: none. But overflow-y doesn't have none) Is ...

Using innerHTML in PHP to create a dynamic two-step echo effect

step 1: I am creating a form where input fields will be dynamically generated using innerHTML. var d = document.getElementById("d1p_1"); d.innerHTML += "<input class='add' name='field_" + i + "' type='text'>"; step 2: ...

The values inputted through the slider on forms are not stored unless they are manually typed into the form

Having spent a couple of days trying to figure this out, I am encountering an issue where the values selected using the slider are not being saved unless I manually click into the forms and press a key on the keyboard. Only then do they get saved and displ ...

Office Outlook Client experiencing incorrect div width

I'm having trouble sending an email with HTML content because it's not displaying correctly in Microsoft Office Outlook when it comes to width. Any suggestions on how to fix this issue? <div style="width: 650px; border: 1px solid blue">hel ...

What's the best way to showcase certain data from a JSON object in a structured table format?

{"symbol":"DRREDDY","series":"EQ","openPrice":"3,132.00","highPrice":"3,229.90","lowPrice":"3,132.00","ltp":"3,206.35","previousPrice":"3,153.25","netPrice":"1.68","tradedQuantity":"74,165","turnoverInLakhs":"2,379.33","lastCorpAnnouncementDate":"18-Jul-20 ...

The "if" statement carries out the identical action each time it is executed

Despite my efforts to toggle the value of the turn variable every time the if statement runs, I keep encountering the same outcome. It appears that turn consistently evaluates as 2. Below is the code snippet in question: $(function() { var turn = 2; ...

The issue with Selenium chromedriver is that it is failing to execute the JavaScript scripts

Normally, the page loads like this: https://i.sstatic.net/GHSb4.png However, when opened with Chrome driver via Selenium in Python, it loads like this: https://i.sstatic.net/dO3Q2.png I have been trying to figure out how to execute JavaScript scripts on ...

The live updates for user data in Firestore are not being reflected immediately when using valueChanges

Utilizing Angular and Cloud Firestore for my backend, I have a setup where users can follow or unfollow each other. The issue arises when the button text and list of followers/following do not immediately update on the front end after a successful click ev ...