When using ChartJS, to set the Y-axis title, you typically need to modify the scales property within the chart's configuration options. Here is a step-by-step guide with code examples to help you understand how to add a title to the Y-axis.
Step 1: Include the ChartJS Library
First, ensure that your project has correctly included the ChartJS library. You can achieve this by using a CDN or downloading the library locally.
html<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
Step 2: Create the Canvas
In your HTML file, add a <canvas> element so that ChartJS can render the chart within it.
html<canvas id="myChart"></canvas>
Step 3: Configure the Chart
In JavaScript, create the chart's configuration object. The key focus is the scales property, specifically the yAxes array, where you can set the scaleLabel property to define the Y-axis title.
javascriptvar ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', // chart type, using a bar chart as an example data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ scaleLabel: { display: true, labelString: 'Number of Votes' } }] } } });
Step 4: View the Result
Open the HTML file containing the above code in a browser, and you should see a bar chart with the Y-axis title "Number of Votes".
By implementing this approach, you can add a clear title to the Y-axis in ChartJS, significantly improving the chart's readability.