AngularJS v1.6.6与angular-chart v1.1.1双Y轴及标签显示定制
Hey there! Let's fix those two chart issues you're facing with AngularJS v1.6.6 and angular-chart v1.1.1. I’ve worked with this stack before, so here’s a step-by-step solution:
1. Align Dual Y-Axis Scales
Right now your right Y-axis is displaying wonky values because it’s calculating its scale independently of the left axis. To make both axes match perfectly, we need to force them to use identical min/max values and tick intervals. Here’s how to update your chart options:
$scope.options = { scales: { yAxes: [ { id: 'y-axis-1', type: 'linear', display: true, position: 'left', // Set base scale bounds (adjust based on your data range) suggestedMin: 0, suggestedMax: 200, ticks: { stepSize: 20 // Consistent tick spacing } }, { id: 'y-axis-2', type: 'linear', display: true, position: 'right', // Mirror left axis scale settings exactly suggestedMin: 0, suggestedMax: 200, ticks: { stepSize: 20 }, // Optional: Hide right axis grid lines to avoid visual clutter gridLines: { display: false } } ] } };
If your data range changes dynamically, you can calculate suggestedMin and suggestedMax from your datas array instead of hardcoding. For example, find the maximum value in datas and add a small buffer to set suggestedMax.
2. Show Permanent Labels on Bars
By default, angular-chart (which wraps Chart.js) doesn’t display labels on bars unless you hover. To fix this, we’ll use the chartjs-plugin-datalabels plugin to add persistent, visible labels. Here’s how to set it up:
First, add the chartjs-plugin-datalabels script to your project (make sure it loads after Chart.js and angular-chart). Then update your controller code to enable and configure the plugin:
angular.module("app", ["chart.js"]) .controller("ChartCtrl", function($scope) { $scope.datas = [ [132], [170], [2.50], [45.67], [154], [89], [111], [160], [94] ]; $scope.labelsdata = ["today"]; $scope.series = ["label1", "label2", "label3", "label4", "label5", "label6", "label7", "label8", "label9"]; $scope.type = $scope.labelsdata.length > 1 ? 'line' : 'bar'; $scope.options = { // Enable the datalabels plugin plugins: { datalabels: { display: true, // Position labels at the top of each bar anchor: 'end', align: 'top', // Extract value from your nested data arrays formatter: function(value) { return value[0]; }, style: { color: '#333', fontSize: 12, fontWeight: 'bold' } } }, scales: { yAxes: [ { id: 'y-axis-1', type: 'linear', display: true, position: 'left', suggestedMin: 0, suggestedMax: 200, ticks: { stepSize: 20 } }, { id: 'y-axis-2', type: 'linear', display: true, position: 'right', suggestedMin: 0, suggestedMax: 200, ticks: { stepSize: 20 }, gridLines: { display: false } } ] } }; });
This configures labels to show each bar’s value at the top, making it easy to match bars to their corresponding series labels. You can tweak the anchor, align, and styling properties to fit your UI needs.
内容的提问来源于stack exchange,提问作者elenat82

