Search code snippets, questions, articles...

chartjs code snippets

How to customize a title in chart.js
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Jan', 'Feb', 'Mar', 'Apr'],
    datasets: [{
      label: 'Months',
      data: [50, 30, 90, 70]
    }]
  },
  options: {
        plugins: {
            title: {
                display: true,
                text: 'Title goes here ...',
                color: '#0055ff',
                position: 'bottom',
                fullSize: true,
                padding: 30,
                align: 'start',
                font: {
                	family: 'Arial',
                	size: 30,
                    weight: 'bold',
                    style: 'italic',
                    lineHeight: 2.0
                }
            }
        }
    }
});
Assign different colors to each bar of a bar chart in Chart.js
const ctx = document.getElementById('chart_id').getContext('2d');
const myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Orange'],
        datasets: [{
            label: 'Different colors bars',
            data: [90, 100, 80, 50, 70],
            backgroundColor: ["#ed1e1e", "#2269e5", "#fce302", "#04f759", "#fc9700"]
        }]
    }
});
Increase font size of axis labels Chart.js
// If you are using version 3
options: {
    scales: {
        x: {
            ticks: {
                font: {
                    size: 20 //this change the font size
                }
            }
        }
    }
}
Change the color of axis labels in Chart.js
const ctx = document.getElementById('my_chart').getContext('2d');
const myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Label 1", "Label 2", "Label 3", "Label 4", "Label 5"],
        datasets: [{
            label: 'Label Name',
            data: [11, 17, 6, 10, 9]
        }]
    },
    options: {
        scales: {
            x: {
                ticks: {
                    color: '#142ffc'
                }
            }
        }
    }
});
Show vertical line on data point hover Chart.js
var ctx = document.getElementById('myChart');

var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['Label 1', 'Label 2', 'Label 3', 'Label 4'],
        datasets: [{
            label: 'Dataset label',
            data: [60, 40, 50, 35]
        }]
    },
    options: {
        interaction: {
            intersect: false,
            mode: 'index',
        }
    },
    plugins: [{
        afterDraw: chart => {
            if (chart.tooltip?._active?.length) {
                let x = chart.tooltip._active[0].element.x;
                let yAxis = chart.scales.y;
                let ctx = chart.ctx;
                ctx.save();
                ctx.beginPath();
                ctx.moveTo(x, yAxis.top);
                ctx.lineTo(x, yAxis.bottom);
                ctx.lineWidth = 1;
                ctx.strokeStyle = '#ff0000';
                ctx.stroke();
                ctx.restore();
            }
        }
    }],
});
Change color of the line in Chart.js line chart
const ctx = document.getElementById('chart_id').getContext('2d');
const myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['Jan', 'Feb', 'Mar', 'Apr'],
        datasets: [{
            label: 'Month',
            data: [90, 40, 50, 70],
            borderColor: "#084de0" // Place your color here
        }]
    }
});
How to add animations in Chart.js
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
        datasets: [{
            label: 'Month',
            data: [90, 40, 20, 70, 50, 30]
        }]
    },
    options: {
        animations: {
            tension: {
                duration: 1200,
                easing: 'linear',
                from: 1,
                to: 0,
                loop: true
            }
        },
        scales: {
            y: {
                min: 0,
                max: 100
            }
        }
    }
});
Use image as chart datasets background Chart.js
const img = new Image();
img.src = 'https://placeimg.com/640/480/any';
img.onload = function() {
    const ctx = document.getElementById('chart').getContext('2d');
    const fillPattern = ctx.createPattern(img, 'repeat');

    const chart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['Item 1', 'Item 2', 'Item 3'],
            datasets: [{
                data: [90, 80, 90],
                backgroundColor: fillPattern
            }]
        }
    });
};
Add a title to the chart in Chart.js
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Jan', 'Feb', 'Mar', 'Apr'],
    datasets: [{
      label: 'Month',
      data: [10, 20, 50, 30]
    }]
  },
  options: {
        plugins: {
            subtitle: {
                display: true,
                text: 'Title goes here ...',
                color: '#ff0000',
                font: {
                	size: 20
                }
            }
        }
    }
});
Assign a fixed height to chart in Chart.js
<canvas id="myChart" width="400" height="300"></canvas>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<script>
    const ctx = document.getElementById('myChart').getContext('2d');
    const myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['Label 1', 'Label 2', 'Label 3', 'Label 4', 'Label 5', 'Label 6'],
            datasets: [{
                label: 'Title',
                data: [10, 20, 50, 30, 20]
            }]
        },
        options: {
            maintainAspectRatio: false // This will fix the height
        }
    });
</script>
Assign fixed width to the columns of bar chart in Chart.js
var ctx = document.getElementById("my_chart").getContext("2d");

new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Label 1", "Label 2", "Label 3", "Label 4"],
        datasets: [{
            label: "Title on top",
            data: [50, 40, 60, 80],
            backgroundColor: "#1491e5",
            barThickness: 30 // Assign your width here
        }]
    },
    options: {
    	maintainAspectRatio: false
    }
});
Hide scale labels on y-axis Chart.js
var mychart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: {
        scales: {
            y: {
                ticks: {
                    display: false
                }
            }
        }
    }
});
Hide label text on x-axis in Chart.js
var mychart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        scales: {
            x: {
                ticks: {
                    display: false
                }
            }
        }
    }
});
Hide title label of datasets in Chart.js
options: {
    plugins: {
        legend: {
            display: false
        }
    }
}
Make y axis to start from 0 in Chart.js
options: {
    scales: {
        y: {
            beginAtZero: true
        }
    }
}
Assign min and max values to y-axis in Chart.js
options: {
    scales: {
        y: {
            beginAtZero: true,
            max: 100
        }
    }
}
Remove or hide tooltips on data points in Chart.js
options: {
    plugins: {
        tooltip: {
            enabled: false
        }
    }
}
Show data values on charts created using chart.js
<canvas id="myChart" width="400" height="300"></canvas>


<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chartjs-plugin-datalabels.min.js"></script>

<script>
    Chart.register(ChartDataLabels);

    const ctx = document.getElementById('myChart').getContext('2d');
    const myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
            datasets: [{
                label: '# of Votes',
                data: [12, 19, 3, 5, 2, 3]
            }]
        },
        options: {
        maintainAspectRatio: false,
        responsive: true,
        plugins: {
            datalabels: { // This code is used to display data values
                anchor: 'end',
                align: 'top',
                formatter: Math.round,
                font: {
                    weight: 'bold',
                    size: 16
                }
            }
        }
        }
    });
</script>
Hide datasets label in Chart.js
var ctx = document.getElementById("mychart").getContext('2d');

var myChart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: ['Point 1', 'Point 2', 'Point 3', 'Point 4'],
      datasets: [{
         labels: "This will be hide",
         data: [20, 50, 40, 30],
         backgroundColor: ["red", "blue", "orange", "green"]
      }]
   },
   options: {
      legend: {
         display: false //This will do the task
      }
   }
});
Create pie chart in Chart.js
var ctx = document.getElementById("pie_chart").getContext('2d');

var myChart = new Chart(ctx, {
   type: 'pie',
   data: {
      labels: ['Point 1', 'Point 2', 'Point 3', 'Point 4'],
      datasets: [{
         labels: "Pie chart",
         data: [20, 50, 40, 30],
         backgroundColor: ["red", "blue", "orange", "green"]
      }]
   }
});
Create line chart in Chart.js
var ctx = document.getElementById("line_chart").getContext('2d');

var myLineChart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: ['Point 1', 'Point 2', 'Point 3', 'Point 4'],
      datasets: [{
         label: "hello",
         data: [40, 50, 80, 20],
         backgroundColor: "rgba(0,0,0,0)",
         borderColor: "#319fe2"
      }]
   },
   options: {
      
   }
});
Create bar chart in Chart.js
var ctx = document.getElementById('myChart').getContext('2d');

var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
       labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple'],
       datasets: [{
            label: '# of Votes',
            data: [90, 60, 50, 50, 100],
            backgroundColor: "#00AAFB",
       }]
    },
    options: {
       scales: {
            xAxes: [{
               gridLines: {
                  display: false
               }
            }],
            yAxes: [{
               ticks: {
                  beginAtZero: true, 
               },
               gridLines: {
                  display: false
               }
            }]
       }
    }
});
Hide gridlines in Chart.js
scales: {
   x: {
         grid: {
         display: false
      }
   },
   y: {
         grid: {
         display: false
      }
   }
}
Bar chart with circular shape from corner in Chart.js
// If you are using Chart.js version - 3.0.0 and above
var ctx = document.getElementById('my_chart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
        datasets: [{
            label: 'Months',
            data: [100, 40, 90, 80, 50, 30],
            backgroundColor: '#ffadb9',
            borderColor: '#f7072b',
            barThickness: 30,
            borderWidth: 2,
            borderRadius: 20, // This will round the corners
            borderSkipped: false, // To make all side rounded
        }]
    },
    options: {
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});