score:168
there is an official plugin for chart.js 2.7.0+ to do this: datalabels
otherwise, you can loop through the points / bars onanimationcomplete and display the values
preview
html
<canvas id="mychart1" height="300" width="500"></canvas>
<canvas id="mychart2" height="300" width="500"></canvas>
script
var chartdata = {
labels: ["january", "february", "march", "april", "may", "june"],
datasets: [
{
fillcolor: "#79d1cf",
strokecolor: "#79d1cf",
data: [60, 80, 81, 56, 55, 40]
}
]
};
var ctx = document.getelementbyid("mychart1").getcontext("2d");
var myline = new chart(ctx).line(chartdata, {
showtooltips: false,
onanimationcomplete: function () {
var ctx = this.chart.ctx;
ctx.font = this.scale.font;
ctx.fillstyle = this.scale.textcolor
ctx.textalign = "center";
ctx.textbaseline = "bottom";
this.datasets.foreach(function (dataset) {
dataset.points.foreach(function (points) {
ctx.filltext(points.value, points.x, points.y - 10);
});
})
}
});
var ctx = document.getelementbyid("mychart2").getcontext("2d");
var mybar = new chart(ctx).bar(chartdata, {
showtooltips: false,
onanimationcomplete: function () {
var ctx = this.chart.ctx;
ctx.font = this.scale.font;
ctx.fillstyle = this.scale.textcolor
ctx.textalign = "center";
ctx.textbaseline = "bottom";
this.datasets.foreach(function (dataset) {
dataset.bars.foreach(function (bar) {
ctx.filltext(bar.value, bar.x, bar.y - 5);
});
})
}
});
fiddle - http://jsfiddle.net/uh9vw0ao/
score:0
to prevent your numbers from being cut off if they're too close to the top of the canvas:
yaxes: [{
ticks: {
stepsize: math.round((1.05*(math.max.apply(math, mylistofyvalues)) / 10)/5)*5,
suggestedmax: 1.05*(math.max.apply(math, mylistofyvalues)),
beginatzero: true,
precision: 0
}
}]
10 = the number of ticks
5 = rounds tick values to the nearest 5 - all y values will be incremented evenly
1.05 = increases the maximum y axis tick value so the numbers don't get cut off
something similar will work for xaxes too.
score:3
adapted the @ross answer to work with 3.7.0 version of the chartjs
animation: {
duration: 0,
oncomplete: function() {
ctx = this.ctx;
ctx.font = chart.helpers.fontstring(chart.defaults.font.size, chart.defaults.font.style, chart.defaults.font.family);
ctx.textalign = 'center';
ctx.textbaseline = 'bottom';
chartinst = this;
this.data.datasets.foreach(function(dataset, i) {
if(chartinst.isdatasetvisible(i)){
var meta = chartinst.getdatasetmeta(i);
meta.data.foreach(function(bar, index) {
var data = dataset.data[index];
ctx.filltext(data, bar.x, bar.y - 5);
});
}
});
}
}
in this case, animation can be 0 to have a nicer looking, you can disable the hover and the tooltip if you want a more "static" visualization
also, the isdatasetvisible works to get rid of the numbers that stay shown when you hide the dataset in case of multiple datasets
score:5
i edited aaron hudon's answer a little, but only for bar charts. my version adds:
- fade in animation for the values.
- prevent clipping by positioning the value inside the bar if the bar is too high.
- no blinking.
downside: when hovering over a bar that has a value inside it, the value might look a little jagged. i have not found a solution do disable hover effects. it might also need tweaking depending on your own settings.
configuration:
bar: {
tooltips: {
enabled: false
},
hover: {
animationduration: 0
},
animation: {
oncomplete: function() {
this.chart.controller.draw();
drawvalue(this, 1);
},
onprogress: function(state) {
var animation = state.animationobject;
drawvalue(this, animation.currentstep / animation.numsteps);
}
}
}
helpers:
// font color for values inside the bar
var insidefontcolor = '255,255,255';
// font color for values above the bar
var outsidefontcolor = '0,0,0';
// how close to the top edge bar can be before the value is put inside it
var topthreshold = 20;
var modifyctx = function(ctx) {
ctx.font = chart.helpers.fontstring(chart.defaults.global.defaultfontsize, 'normal', chart.defaults.global.defaultfontfamily);
ctx.textalign = 'center';
ctx.textbaseline = 'bottom';
return ctx;
};
var fadein = function(ctx, obj, x, y, black, step) {
var ctx = modifyctx(ctx);
var alpha = 0;
ctx.fillstyle = black ? 'rgba(' + outsidefontcolor + ',' + step + ')' : 'rgba(' + insidefontcolor + ',' + step + ')';
ctx.filltext(obj, x, y);
};
var drawvalue = function(context, step) {
var ctx = context.chart.ctx;
context.data.datasets.foreach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
var model = dataset._meta[object.keys(dataset._meta)[0]].data[i]._model;
var texty = (model.y > topthreshold) ? model.y - 3 : model.y + 20;
fadein(ctx, dataset.data[i], model.x, texty, model.y > topthreshold, step);
}
});
};
score:7
from chart.js samples (file chart.js-2.4.0/samples/data_labelling.html):
// define a plugin to provide data labels
chart.plugins.register({
afterdatasetsdraw: function(chartinstance, easing) {
// to only draw at the end of animation, check for easing === 1
var ctx = chartinstance.chart.ctx;
chartinstance.data.datasets.foreach(function (dataset, i) {
var meta = chartinstance.getdatasetmeta(i);
if (!meta.hidden) {
meta.data.foreach(function(element, index) {
// draw the text in black, with the specified font
ctx.fillstyle = 'rgb(0, 0, 0)';
var fontsize = 16;
var fontstyle = 'normal';
var fontfamily = 'helvetica neue';
ctx.font = chart.helpers.fontstring(fontsize, fontstyle, fontfamily);
// just naively convert to string for now
var datastring = dataset.data[index].tostring();
// make sure alignment settings are correct
ctx.textalign = 'center';
ctx.textbaseline = 'middle';
var padding = 5;
var position = element.tooltipposition();
ctx.filltext(datastring, position.x, position.y - (fontsize / 2) - padding);
});
}
});
}
});
score:7
from my experience, once you include the chartjs-plugin-datalabels plugin (make sure to place the <script>
tag after the chart.js tag on your page), your charts begin to display values.
if you then choose you can customize it to fit your needs. the customization is clearly documented here but basically, the format is like this hypothetical example:
var mybarchart = new chart(ctx, {
type: 'bar',
data: yourdataobject,
options: {
// other options
plugins: {
datalabels: {
anchor :'end',
align :'top',
// and if you need to format how the value is displayed...
formatter: function(value, context) {
return getvalueformatted(value);
}
}
}
}
});
score:8
following this good answer, i'd use these options for a bar chart:
var chartoptions = {
animation: false,
responsive : true,
tooltiptemplate: "<%= value %>",
tooltipfillcolor: "rgba(0,0,0,0)",
tooltipfontcolor: "#444",
tooltipevents: [],
tooltipcaretsize: 0,
onanimationcomplete: function()
{
this.showtooltip(this.datasets[0].bars, true);
}
};
window.mybar = new chart(ctx1).bar(chartdata, chartoptions);
this still uses the tooltip system and his advantages (automatic positionning, templating, ...) but hiding the decorations (background color, caret, ...)
score:9
i'd recommend using this plugin: datalabels
labels can be added to your charts simply by importing the plugin into the javascript file, for example:
import 'chartjs-plugin-datalabels'
and can be fine-tuned using this documentation: https://chartjs-plugin-datalabels.netlify.com/options.html
score:22
i think the nicest option to do this in chart.js v2.x is by using a plugin, so you don't have a large block of code in the options. in addition, it prevents the data from disappearing when hovering over a bar.
i.e., simply use this code, which registers a plugin that adds the text after the chart is drawn.
chart.pluginservice.register({
afterdraw: function(chartinstance) {
var ctx = chartinstance.chart.ctx;
// render the value of the chart above the bar
ctx.font = chart.helpers.fontstring(chart.defaults.global.defaultfontsize, 'normal', chart.defaults.global.defaultfontfamily);
ctx.textalign = 'center';
ctx.textbaseline = 'bottom';
chartinstance.data.datasets.foreach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
var model = dataset._meta[object.keys(dataset._meta)[0]].data[i]._model;
ctx.filltext(dataset.data[i], model.x, model.y - 2);
}
});
}
});
score:26
based on ross's answer for chart.js 2.0 and up, i had to include a little tweak to guard against the case when the bar's heights comes too chose to the scale boundary.
the animation
attribute of the bar chart's option:
animation: {
duration: 500,
easing: "easeoutquart",
oncomplete: function () {
var ctx = this.chart.ctx;
ctx.font = chart.helpers.fontstring(chart.defaults.global.defaultfontfamily, 'normal', chart.defaults.global.defaultfontfamily);
ctx.textalign = 'center';
ctx.textbaseline = 'bottom';
this.data.datasets.foreach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
var model = dataset._meta[object.keys(dataset._meta)[0]].data[i]._model,
scale_max = dataset._meta[object.keys(dataset._meta)[0]].data[i]._yscale.maxheight;
ctx.fillstyle = '#444';
var y_pos = model.y - 5;
// make sure data value does not get overflown and hidden
// when the bar's value is too close to max value of scale
// note: the y value is reverse, it counts from top down
if ((scale_max - model.y) / scale_max >= 0.93)
y_pos = model.y + 20;
ctx.filltext(dataset.data[i], model.x, y_pos);
}
});
}
}
score:35
this animation option works for 2.1.3 on a bar chart.
slightly modified ross answer:
animation: {
duration: 0,
oncomplete: function () {
// render the value of the chart above the bar
var ctx = this.chart.ctx;
ctx.font = chart.helpers.fontstring(chart.defaults.global.defaultfontsize, 'normal', chart.defaults.global.defaultfontfamily);
ctx.fillstyle = this.chart.config.options.defaultfontcolor;
ctx.textalign = 'center';
ctx.textbaseline = 'bottom';
this.data.datasets.foreach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
var model = dataset._meta[object.keys(dataset._meta)[0]].data[i]._model;
ctx.filltext(dataset.data[i], model.x, model.y - 5);
}
});
}
}
score:38
if you are using the plugin chartjs-plugin-datalabels then the following code options object will help.
make sure you import import 'chartjs-plugin-datalabels';
in your typescript file or add reference to <script src="chartjs-plugin-datalabels.js"></script>
in your javascript file.
options: {
maintainaspectratio: false,
responsive: true,
scales: {
yaxes: [{
ticks: {
beginatzero: true,
}
}]
},
plugins: {
datalabels: {
anchor: 'end',
align: 'top',
formatter: math.round,
font: {
weight: 'bold'
}
}
}
}
score:93
this works for chart.js 2.3, including for both line/bar types.
important: even if you don't need the animation, don't change the duration option to 0. otherwise, you will get chartinstance.controller is undefined error.
var chartdata = {
labels: ["january", "february", "march", "april", "may", "june"],
datasets: [
{
fillcolor: "#79d1cf",
strokecolor: "#79d1cf",
data: [60, 80, 81, 56, 55, 40]
}
]
};
var opt = {
events: false,
tooltips: {
enabled: false
},
hover: {
animationduration: 0
},
animation: {
duration: 1,
oncomplete: function () {
var chartinstance = this.chart,
ctx = chartinstance.ctx;
ctx.font = chart.helpers.fontstring(chart.defaults.global.defaultfontsize, chart.defaults.global.defaultfontstyle, chart.defaults.global.defaultfontfamily);
ctx.textalign = 'center';
ctx.textbaseline = 'bottom';
this.data.datasets.foreach(function (dataset, i) {
var meta = chartinstance.controller.getdatasetmeta(i);
meta.data.foreach(function (bar, index) {
var data = dataset.data[index];
ctx.filltext(data, bar._model.x, bar._model.y - 5);
});
});
}
}
};
var ctx = document.getelementbyid("chart1"),
mylinechart = new chart(ctx, {
type: 'bar',
data: chartdata,
options: opt
});
<canvas id="mychart1" height="300" width="500"></canvas>
Source: stackoverflow.com
Related Query
- How to display data values on Chart.js
- How to display inline values in a stacked bar chart with Chart.js?
- How to display data labels outside in pie chart with lines in ionic
- How can I display the xAxes and yAxes data in the tooltip, Chart JS?
- How to show data values in top of bar chart and line chart in chart.js 3
- How to commaize the data values provided to a chart in Chart.JS?
- how to display chart data as html table chartjs
- How to display chart using Chartjs with JSON data in Laravel
- How do I get a chart.js chart to display data in a Node/React web application?
- How do I display chart on my HTML page based on JSON data sent by Node JS
- Chart JS how to display an array of data objects as bar chart
- How to get Data from API to display chart using chartjs in Vuejs
- How to show the chartjs bar chart data values labels as text?
- How can i display my data in a chart using chart js
- Chart.js How to sum the values in a pie chart and display them in the header
- Chart.js How can I embed additional values to each data point in radar chart
- How to display the values inside the pie chart of PrimeNG (chart) using JavaScript or Angular
- How can I get my Chart.JS bar chart to stack two data values together on each bar, and print a calculated value on each bar?
- How to stop displaying the data values from different data objects on Chart JS 2.x?
- How do I destroy/update Chart Data in this chart.js code example?
- How to adding data in loop and display chart dynamically like in live (chart.js & typescript & angular)?
- how to display table from chart js data in canvas.js using java script .?
- How to display data values on bar graph (chart.js)?
- How to display data on hover inside doughnut chart in Angular Chart?
- How to set data values as labels in Chart.js with a Radar Chart
- line chart with {x, y} point data displays only 2 values
- How to display Line Chart dataset point labels with Chart.js?
- chart js tooltip how to control the data that show
- Display values outside of pie chart in chartjs
- How to display value of only one datapoint in line chart
More Query from same tag
- Only first value added gets displayed in ng2-chart linechart
- Chart.js, dashed line, full width chart
- c# Chart.Js and JSON with NewtonSoft
- How to make bar charts and scatter dots appear underneath each other?
- Error: "category" is not a registered scale
- Uncaught ReferenceError: Chart is not defined at test.html:11
- Why does x axis not increment 'monthly' chart.js. Also, XAxis not taking title
- Draw a horizontal bar chart from right to left
- Chart.js will not render using vue.js until window resizes
- Chart JS not working with Phonegap
- How can I specify "per dataset" parsing with Chart.js?
- Bar chart does not appear with Chart.js
- How can I express this element?
- Possible to merge 2 bars in bar chart (chart.js)
- Chart.js - Line charts: draw points between grid lines
- How can I create a horizontal scrolling Chart.js line chart with a locked y axis?
- Animate Chartist on show
- Type 'string' is not assignable to type 'ChartType'
- End x-axis on last data point (scatter plot) for x,y numeric values
- i18n with chart.js (javascript)
- update my chartjs form without refreshing page
- Can't find the chart.js v2 docs
- Javascript chart.js data object/array
- Display character after y-axis data value in onhover pop up Chart.js
- How to align labels at same side chartjs React
- Chart.js update() method only works once in the end instead of updating every iteration
- Chart.js 2.x: labels displaying over eachother
- Chartjs: How to programatically remove (unhighlight or make inactive) all the active points on chart
- How do I use Chart.js and Bootstrap at same time? (various jQuery versions)
- Highlight a particular point in chart JS