How to properly use the chartjs datalabels plugin - plugins

I'm using Chart.js to create a bar char, I have to display the percentage on each bar, so I found the chartjs-plugin-datalabels, but I can't make it work, the documentation and the examples are not clear for me.
This is What I got:
HTML:
<canvas id="bar-chart" width="800" height="450"></canvas>
Javascript:
// Bar chart
var valuedata= [2478,5267,734,784,433];
var valuelabel=["Africa", "Asia", "Europe", "Latin America", "North America"];
var myBarChart = new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels: valuelabel,
datasets: [
{
label: "Population (millions)",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: valuedata,
}
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Predicted world population (millions) in 2050'
},
scales: {
xAxes: [{
gridLines: {
display:false
}
}],
yAxes: [{
gridLines: {
display:false,
drawBorder: false
},
ticks: {
display: false
}
}]
},
plugins: {
datalabels: {
color: 'white',
display: function(context) {
console.log("Algo: "+context);
return context.dataset.data[context.dataIndex] > 15;
},
font: {
weight: 'bold'
},
formatter: function(value, context) {
return context.dataIndex + ': ' + Math.round(value*100) + '%';
}
}
}
}
});
myBarChart.update();
Supposedly, from what I get, the "plugin" inside option is the one that let the values to be display, but as I shown in my code above, doesn't work for me, surely I'm missing something but I don't know what, can somebody help me?
Thanks.
Fiddle:
https://jsfiddle.net/s64bq4sw/16/

It was because of the version of the Chartjs I was using, this plugin requieres 2.7.0 or later.

Related

Custom tooltip title based on dictionary mapping of values

MWE: See a graph below with countries in the x-axis. What is the best way to show the whole name in the tooltip instead of the acronym? (Show "Germany" instead of "GER", France instead of "FRA", etc.). I have like 10 or 15 of those.
SEE FULL CODE IN jsfiddle
var example2 = [229, 113, 109];
var labels2 = ["GER", "FRA", "LT"];
https://jsfiddle.net/user3507584/6zpb715x/6/
You can add an object with translations where the key is the value from the label and the value is the full country name:
var example2 = [229, 113, 109];
var labels2 = ["GER", "FRA", "LT"];
var translations = {
GER: 'Germany',
FRA: 'France',
LT: "Italy"
}
var barChartData2 = {
labels: labels2,
datasets: [{
label: 'Student Count',
backgroundColor: '#ccece6',
data: example2
}]
};
function drawChart(el, data, title) {
var ctx = document.getElementById(el).getContext("2d");
var bar = new Chart(ctx, {
type: 'bar',
data: data,
options: {
// Elements options apply to all of the options unless overridden in a dataset
// In this case, we are setting the border of each bar to be 2px wide and green
elements: {
rectangle: {
borderWidth: 2,
borderColor: '#98c4f9',
borderSkipped: 'bottom'
}
},
responsive: true,
legend: {
position: 'bottom',
},
title: {
display: true,
text: title
},
scales: {
yAxes: [{
ticks: {
beginAtZero: 0,
min: 0
}
}],
xAxes: [{
ticks: {
// Show all labels
autoSkip: false,
callback: function(tick) {
var characterLimit = 20;
if (tick.length >= characterLimit) {
return tick.slice(0, tick.length).substring(0, characterLimit - 1).trim() + '...';;
}
return tick;
}
}
}]
},
tooltips: {
callbacks: {
title: function(tooltipItem) {
return translations[tooltipItem[0].xLabel];
}
}
}
}
});
console.log(bar);
};
drawChart('canvas0', barChartData2, 'example title');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.js"></script>
<div id="container">
<canvas id="canvas0"></canvas>
</div>

Chart.js place both series on same scale

So I have a chart.js chart with two series. One is a bar chart and the other is a line graph.
S1 = 71,166,2,6,8
S2 = 6,2,4,8,5
When I plot them, they both appear on their own scales which makes the bar and line graphs kinda pointless.
I need a way to plot both charts on the same scale.
Is there a way to do this within chart.js? If not, how would you do it?
thanks.
var barChartData = {
labels: dataLabels,
datasets: [{
type: 'bar',
label: "Actual",
data: dataActual,
fill: false,
backgroundColor: '#71B37C',
borderColor: '#71B37C',
hoverBackgroundColor: '#71B37C',
hoverBorderColor: '#71B37C',
yAxisID: 'y-axis-2'
}, {
label: "Maximum",
type:'line',
data: dataMaximum,
fill: false,
borderColor: '#EC932F',
backgroundColor: '#EC932F',
pointBorderColor: '#EC932F',
pointBackgroundColor: '#EC932F',
pointHoverBackgroundColor: '#EC932F',
pointHoverBorderColor: '#EC932F',
yAxisID: 'y-axis-1'
} ]
};
$(function () {
if (theChart !== undefined) {
theChart.destroy();
}
var ctxActualVsMax = document.getElementById("myChart2").getContext("2d");
theChart = new Chart(ctxActualVsMax, {
type: 'bar',
data: barChartData,
options: {
responsive: true,
tooltips: {
mode: 'label'
},
elements: {
line: {
fill: false
}
},
scales: {
xAxes: [{
display: true,
gridLines: {
display: false
},
labels: {
show: true,
}
}],
yAxes: [{
type: "linear",
display: true,
position: "left",
id: "y-axis-1",
gridLines:{
display: false
},
labels: {
show:true,
}
}, {
type: "linear",
display: false,
position: "right",
id: "y-axis-2",
gridLines:{
display: false
},
labels: {
show:true,
}
}]
}
}
});
});
In your code you have specified your two datasets to use different yAxisId's. Just set them both to the same, you can also remove the unused yAxes object from the options
fiddle

How to apply flat colors effect in Kendo charts

I am using Telerik charts in my project. I am able to change the color of charts but not the style. What i mean by style is - there appears a embossed effect over all the charts(First Image). What i need to apply is flat colors(Second Image). How can i remove gradient effect over charts in all my Kendo charts?
Thanks in advance.
You have to apply Overlay effect. See this Kendo Document
Apply none gradient option and available gradient options are :
roundedBevel (This is the default gradient option)
sharpBevel
none
function createChart() {
$("#chart").kendoChart({
title: {
position: "bottom",
text: "Share of Internet Population Growth, 2007 - 2012"
},
legend: { visible: false },
chartArea: { background: "" },
seriesDefaults: {
labels: {
visible: true, background: "transparent", template: "#= category #: \n #= value#%"
}
},
series: [{
type: "pie",
overlay: { gradient: "none" },
startAngle: 150,
data: [{ category: "Asia", value: 53.8, color: "#9de219" },
{ category: "Europe", value: 16.1, color: "#90cc38" },
{ category: "Latin America", value: 11.3, color: "#068c35" },
{ category: "Africa", value: 9.6, color: "#006634" },
{ category: "Middle East", value: 5.2, color: "#004d38" },
{ category: "North America", value: 3.6, color: "#033939" }]
}],
tooltip: { visible: true, format: "{0}%" }
});
}
$(document).ready(createChart);
<link rel="stylesheet" type="text/css" href="//kendo.cdn.telerik.com/2016.1.226/styles/kendo.common-material.min.css" />
<link rel="stylesheet" type="text/css" href="//kendo.cdn.telerik.com/2016.1.226/styles/kendo.material.min.css" />
<script src="//kendo.cdn.telerik.com/2016.1.226/js/jquery.min.js"></script>
<script src="//kendo.cdn.telerik.com/2016.1.226/js/kendo.all.min.js"></script>
<div id="chart" ></div>
Please try with the below code snippet. To remove gradient effect you have to set 'overlay: null' in chart.
<div id="chart"></div>
<script>
var data = [
{
"source": "Hydro",
"percentage": 22,
"explode": true
},
{
"source": "Solar",
"percentage": 2
},
{
"source": "Nuclear",
"percentage": 49
},
{
"source": "Wind",
"percentage": 27
}
];
$(document).ready(function () {
$("#chart").kendoChart({
title: {
text: "Break-up of Spain Electricity Production for 2008"
},
legend: {
position: "bottom"
},
dataSource: {
data: data
},
seriesDefaults: {
overlay: {
gradient: null
}
},
series: [{
type: "pie",
field: "percentage",
categoryField: "source",
explodeField: "explode"
}],
seriesColors: ["#03a9f4", "#ff9800", "#fad84a", "#4caf50"],
tooltip: {
visible: true,
template: "${ category } - ${ value }%"
}
});
});
</script>
Let me know if any concern.

In Chart.js set chart title, name of x axis and y axis?

Does Chart.js (documentation) have option for datasets to set name (title) of chart (e.g. Temperature in my City), name of x axis (e.g. Days) and name of y axis (e.g. Temperature). Or I should solve this with css?
var lineChartData = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : [data]
}
]
}
Realy thanks for help.
In Chart.js version 2.0, it is possible to set labels for axes:
options = {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}]
}
}
See Labelling documentation for more details.
For Chart.js version 3
options = {
scales: {
y: {
title: {
display: true,
text: 'Your Title'
}
}
}
}
If you have already set labels for your axis like how #andyhasit and #Marcus mentioned, and would like to change it at a later time, then you can try this:
chart.options.scales.yAxes[ 0 ].scaleLabel.labelString = "New Label";
Full config for reference:
var chartConfig = {
type: 'line',
data: {
datasets: [ {
label: 'DefaultLabel',
backgroundColor: '#ff0000',
borderColor: '#ff0000',
fill: false,
data: [],
} ]
},
options: {
responsive: true,
scales: {
xAxes: [ {
type: 'time',
display: true,
scaleLabel: {
display: true,
labelString: 'Date'
},
ticks: {
major: {
fontStyle: 'bold',
fontColor: '#FF0000'
}
}
} ],
yAxes: [ {
display: true,
scaleLabel: {
display: true,
labelString: 'value'
}
} ]
}
}
};
For Readers in 2021:
Version
"chart.js": "^3.3.2",
Real World Working Sample:
const optionsTemplate = (yAxisTitle, xAxisTitle) => {
return {
scales: {
yAxes: {
title: {
display: true,
text: yAxisTitle,
font: {
size: 15
}
},
ticks: {
precision: 0
}
},
xAxes: {
title: {
display: true,
text: xAxisTitle,
font: {
size: 15
}
}
}
},
plugins: {
legend: {
display: false,
}
}
}
}
In chart JS 3.5.x, it seems to me the title of axes shall be set as follows (example for x axis, title = 'seconds'):
options: {
scales: {x: { title: { display: true, text: 'seconds' }}}
}
see: https://www.chartjs.org/docs/latest/axes/labelling.html
just use this:
<script>
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["1","2","3","4","5","6","7","8","9","10","11",],
datasets: [{
label: 'YOUR LABEL',
backgroundColor: [
"#566573",
"#99a3a4",
"#dc7633",
"#f5b041",
"#f7dc6f",
"#82e0aa",
"#73c6b6",
"#5dade2",
"#a569bd",
"#ec7063",
"#a5754a"
],
data: [12, 19, 3, 17, 28, 24, 7, 2,4,14,6],
},]
},
//HERE COMES THE AXIS Y LABEL
options : {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}]
}
}
});
</script>
If you are using chart JS v4 try this.
options = {
scales: {
y: {
title: {
display: true,
text: 'Test'
}
},
x: {
title: {
display: true,
text: 'Test'
}
}
},
plugins: {
legend: {
display: false,
},
}
}
<Scatter
data={data}
// style={{ width: "50%", height: "50%" }}
options={{
scales: {
yAxes: [
{
scaleLabel: {
display: true,
labelString: "Probability",
},
},
],
xAxes: [
{
scaleLabel: {
display: true,
labelString: "Hours",
},
},
],
},
}}
/>
See example with name of x axis and y axis left and right.
public barChartOptions: ChartOptions = {
title: {
display: true,
text: 'Custom Chart Title',
},
responsive: true,
legend: {
position: 'right',
},
scales: {
yAxes: [
{
position: 'right',
scaleLabel: {
display: true,
labelString: 'Frequency Rate - right',
},
},
{
position: 'left',
scaleLabel: {
display: true,
labelString: 'Frequency Rate - left',
},
},
],
xAxes: [
{
display: true,
position: 'bottom',
scaleLabel: {
display: true,
labelString: 'Titulo do eixo X',
fontStyle: 'italic',
fontSize: 12,
fontColor: '#030',
},
},
],
},
};

Kendo ui chart hide circle for data points

I'm not able to hide rounded circle for the line chart in Kendo ui. I do want to show tooltip value but want to hide circle.
below example is from demo site: http://demos.kendoui.com/dataviz/line-charts/index.html
Even, I don't know what do they call it so that I can find in the document here: http://docs.kendoui.com/api/dataviz/chart
According to the docs, you can set series.markers.visible to false:
http://docs.telerik.com/kendo-ui/api/javascript/dataviz/ui/chart#configuration-series.markers.visible
Additionally you can change their size and shape.
Please try with the below code snippet. Let me know if any concern.
<style>
#chart circle {
display: none !important;
}
</style>
<script>
function createChart() {
$("#chart").kendoChart({
title: {
text: "Gross domestic product growth /GDP annual %/"
},
legend: {
position: "bottom"
},
chartArea: {
background: ""
},
seriesDefaults: {
type: "line"
},
series: [{
name: "India",
data: [3.907, 7.943, 7.848, 9.284, 9.263, 9.801, 3.890, 8.238, 9.552, 6.855]
}, {
name: "World",
data: [1.988, 2.733, 3.994, 3.464, 4.001, 3.939, 1.333, -2.245, 4.339, 2.727]
}, {
name: "Russian Federation",
data: [4.743, 7.295, 7.175, 6.376, 8.153, 8.535, 5.247, -7.832, 4.3, 4.3]
}, {
name: "Haiti",
data: [-0.253, 0.362, -3.519, 1.799, 2.252, 3.343, 0.843, 2.877, -5.416, 5.590]
}],
valueAxis: {
labels: {
format: "{0}%"
},
line: {
visible: false
},
axisCrossingValue: -10
},
categoryAxis: {
categories: [2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011],
majorGridLines: {
visible: false
}
},
tooltip: {
visible: false
}
});
}
$(document).ready(createChart);
</script>