Skip to content

Commit

Permalink
Added data labels to chart.js
Browse files Browse the repository at this point in the history
  • Loading branch information
lucascumsille authored and zarino committed Oct 14, 2024
1 parent 71a4111 commit dcc1a65
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 4 deletions.
23 changes: 20 additions & 3 deletions hub/static/js/area.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import $ from 'jquery/dist/jquery.slim'
import { Chart, BarController, BarElement, CategoryScale, LinearScale, Legend, Tooltip } from 'chart.js'
import ChartDataLabels from 'chartjs-plugin-datalabels';
import trackEvent from './analytics.esm.js'
import setUpCollapsable from './collapsable.esm.js'
import Dropdown from 'bootstrap/js/dist/dropdown'

Chart.register( BarController, BarElement, CategoryScale, LinearScale, Legend, Tooltip);

Chart.register( BarController, BarElement, CategoryScale, LinearScale, Legend, Tooltip, ChartDataLabels);

Chart.defaults.font.family = '"Public Sans", sans-serif'
Chart.defaults.font.size = 12
Expand Down Expand Up @@ -156,7 +158,7 @@ var makeChart = function() {
var $table = $(this)
var chartType = $table.data('chart-type') || 'bar'
var chartWidth = $table.data('chart-width') || 600
var rowHeight = $table.data('row-height') || 40
var rowHeight = $table.data('row-height') || 80
var legendHeight = 60
var labelHeight = 60
var $div = $('<div>').attr({'class': 'chartwrapper'})
Expand All @@ -179,6 +181,12 @@ var makeChart = function() {
},
options: {
indexAxis: primaryAxis,
layout: {
padding: {
// Some extra padding for the data labels.
right: 30
}
},
scales: {
[crossAxis]: {
ticks: {
Expand Down Expand Up @@ -211,7 +219,16 @@ var makeChart = function() {
return context.dataset.label + ': ' + (context.raw / 100).toLocaleString('en-GB', { style: 'percent' });
}
}
}
},
datalabels: {
formatter: function(value) {
return value + '%'; // Adds percentage to the data label
},
color: '#6c757d',
anchor: 'end',
align: 'end',
offset: 5,
},
}
}
}
Expand Down
12 changes: 11 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"@popperjs/core": "^2.11.8",
"bootstrap": "^5.3.2",
"chart.js": "^4.4.1",
"chartjs-plugin-datalabels": "^2.2.0",
"jquery": "^3.7.1",
"leaflet": "^1.9.4",
"leaflet-geosearch": "^4.0.0",
Expand Down

0 comments on commit dcc1a65

Please sign in to comment.