Add Labels to Chart.js Bar Chart - javascript

I am trying to add labels to my bar chart. See the JS fiddle and code below. How would I change my code to add labels?
http://jsfiddle.net/amwmedia/8kqvyhqv/
var myNewChart;
var data = [
{
value: 30,
label: "hello",
color: "#F7464A"
}, {
value: 50,
color: "#E2EAE9"
}, {
value: 100,
color: "#D4CCC5"
}, {
value: 40,
color: "#949FB1"
}, {
value: 100,
color: "#4D5360"
},
];
var options = {
animation: true,
animationEasing: 'easeInOutQuart',
animationSteps: 80,
multiTooltipTemplate: "<%= datasetLabel %> - <%= value %>"
};
var ctx = document.getElementById("myChart")
.getContext("2d");
myNewChart = new Chart(ctx).Doughnut(data, options);

I noticed your jsfiddle is using chart.js version 1. My answer uses version 2, as that is all I could find documentation for.
Looks like all you need to do is put labels in the data object:
var data = {
labels: [
"label1",
"label2",
"label3",
"label4",
"label5"
],
datasets: [
{
data: [
30,
50,
100,
40,
100
],
backgroundColor:[
'#F7464A',
'#E2EAE9',
'#D4CCC5',
'#949FB1',
'#4D5360'
]
}]
};
See fiddle. (this is using Chart.js 2.0)

Related

Custom colors in C3.js timeseries chart

I am trying to set custom colors in a c3.js timeseries chart following this example. The first element of each array is used to identify the dataset, so if I have an array:
var datatest1 = ['data1', 30, 200, 100, 400, 150, 250];
the color property can be accessed like this:
colors: {data1:'#0000'}
or:
colors: {'data1':'#0000'}
However, if I use the first element of the array to access them:
var data1id = datatest1[0];
and then:
colors: {data1id:'#0000'}
It fails. Not sure what I may doing wrong as I get no feedback in the browser...
Here is a working example:
var axis = ['x', '2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04', '2013-01-05', '2013-01-06'];
var datatest2 = ['data2', 130, 340, 200, 500, 250, 350];
var datatest1 = ['data1', 30, 200, 100, 400, 150, 250];
var data1id = datatest1[0];
var data2id = datatest2[0];
var chart = c3.generate({
data: {
x: 'x',
columns: [
axis,
datatest1,
datatest2
],
colors: {
//data1: '#0000',
//data2: '#0000'
datatest1: '#0000',
datatest2: '#0000'
}
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%Y-%m-%d'
}
}
}
});
----- EDIT
I am doing this because the data (including the identifier) is generated dynamically. Thanks
You can dynamically create the colors object like this.
var colors = {};
colors[datatest1[0]] = '#0000';
colors[datatest2[0]] = '#0000';
then set it in the graph like this
var chart = c3.generate({
data: {
x: 'x',
columns: [
axis,
datatest1,
datatest2
],
colors: colors //set colors object created above
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%Y-%m-%d'
}
}
}
});
working code here

how to setting chart js customization

I want to use chart.js in my websites. I am successfully implemented with the code below
var doughnutData = [
{
value: 30,
color:"#f91942",
},
{
value : 50,
color : "#0b7bb5"
},
{
value : 120,
color : "#4D5360"
}
];
var labels = [
'Red',
'Yellow',
'Blue'
];
var myDoughnut = new Chart(document.getElementById("canvas").getContext("2d")).Doughnut(doughnutData);
</script>`
The result is like this
Now I want to know that is there anywhere to make the column show the number when mouse hover and adding a label for each column?
Add label with your data to show it in the tooltip
var doughnutData = [{
value: 30,
color: "#f91942",
label: 'Red'
}, {
value: 50,
color: "#0b7bb5",
label: 'Yellow'
}, {
value: 120,
color: "#4D5360",
label: 'Blue'
}];
This will display tooltip with default template
<%if (label){%><%=label%>: <%}%><%= value %>
Which show like
Red: 30
You can change the template using tooltipTemplate key, like below
var options: {
tooltipTemplate: "This value is -> <%= value %>"
};
var myDoughnut = new Chart(document.getElementById("canvas").getContext("2d")).Doughnut(data, options);
This will give you
This value is -> 50

How to show gradient vertically on chart js grouped bar chart?

I am using Chart.js grouped bar chart. I want to show my bars with gradient colors. Currently it show as shown in below image. Any help will be greatly appreciated.
var rateOfReturn= document.getElementById("rateofreturn-chart-canvas").getContext('2d');
var rateOfReturnData = {
labels: ["Monthly", "Quarterly", "Semiannually", "Annually"],
datasets: [
{
label: "label1",
backgroundColor: [
'#26343b',
'#26343b',
'#26343b',
'#26343b'
],
data: [4, 6, 8, -3],
},
{
label: "",
backgroundColor: [
'#be1a33',
'#be1a33',
'#be1a33',
'#be1a33'
],
data: [6, 10, 11, 7],
},
{
label: "",
backgroundColor: [
'#00b786',
'#00b786',
'#00b786',
'#00b786'
],
data: [13, 10, 9, 4],
},
{
label: "",
backgroundColor: [
'#f86929',
'#f86929',
'#f86929',
'#f86929'
],
data: [6, 8, 2, 11],
},
{
label: "",
backgroundColor: [
'#046cd0',
'#046cd0',
'#046cd0',
'#046cd0'
],
data: [4, 8, 7, 13],
}
]
};
rateOfReturn.canvas.height = 80;
var myBarChart = new Chart(rateOfReturn, {
type: 'bar',
data: rateOfReturnData,
options: {
legend:
{
display: false
},
scales:
{
xAxes: [{
title: "Test title",
ticks: {
beginAtZero: true,
titleFontWeight: "bold"
},
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Rate Of Return (ROR) % '
},
ticks: {
beginAtZero:true,
mirror:false,
suggestedMin: 0
},
}]
}
}
});
You want to use Chart.js plugins. They let you handle some events triggered through the chart creation such as the initialization, the resize, etc.
Chart.pluginService.register({
beforeUpdate: function(chart) {
// All the code added here will be executed before a chart update
}
});
You also want to use createLinearGradient to create a gradient color usable in a canvas :
var gradient = ctx.createLinearGradient(0,0,200,0); // Dimensions of the color rectangle
gradient.addColorStop(0,"green"); // First color
gradient.addColorStop(1,"white"); // Second color
Now you want to use both into one. Let's first see how it works.
You first have to add the two colors of the gradient you want to see in your chart data :
datasets: [{
label: "label1",
backgroundColor: [
['#26343b', 'white'], // `white` and `#FFFFFF` both stand for a white color
['#26343b', 'white'],
['#26343b', 'white'],
['#26343b', 'white']
],
data: [4, 6, 8, -3],
}, {
// ...
}]
Then you need to add the following plugin before you create the chart (using new Chart()), or else it won't be added into the chart's plugin service :
Chart.pluginService.register({
beforeUpdate: function(chart) {
// For every dataset ...
for (var i = 0; i < chart.config.data.datasets.length; i++) {
// We store it
var dataset = chart.config.data.datasets[i];
// For every data in this dataset
for (var j = 0; j < dataset.data.length; j++) {
// We store the data model (graph information)
var model = dataset._meta[0].data[j]._model;
// We use the model to get the left & right borders X position
// and to create the gradient
var start = model.x,
end = model.x + model.width,
gradient = rateOfReturn.createLinearGradient(start, 0, end - 5, 0);
// The colors of the gradient that were defined in the data
gradient.addColorStop(0, dataset.backgroundColor[j][0]);
gradient.addColorStop(1, dataset.backgroundColor[j][1]);
// We set this new color to the data background
dataset.backgroundColor[j] = gradient;
}
}
}
});
Follows the result of the plugin with your example, which you can find on this jsFiddle :

Chart.js stacked and grouped horizontalBar chart

I've been trying to display somewhat complex data on my webpage and chose chart.js to do so.
Therefor I need to group multiple stacked bars horizontally.
I already found this fiddle for "normal" bars but couldn't quite change it to work with horizontalBar yet.
Stackoverflow question: Chart.js stacked and grouped bar chart
The original Fiddle (http://jsfiddle.net/2xjwoLq0/) has
Chart.defaults.groupableBar = Chart.helpers.clone(Chart.defaults.bar);
And I just replaced the .bar everywhere in the code with .horizontalBar (well knowing that this won't make the cut).
Chart.defaults.groupableBar = Chart.helpers.clone(Chart.defaults.horizontalBar);
Since that didn't quite work, I tried adding the second stacked modifier as suggested for horizontal bars here:
Horizontal stacked bar chart with chart.js and flipped the functions for X and Y calculation (calculateBarY/calculateBarX)
Which quite work either because the stacks won't get merged onto each other correctly.
http://jsfiddle.net/2xjwoLq0/3/
I would appreciate if anyone could help me out on this one.
Looking for something similar, I took a look on example you gave, and decide to write something.
Rather than trying to fix the code or reusing the 'groupableBar', I get Chart.js code from Chart.controllers.horizontalBar and rewrite some part in functions calculateBarY, calculateBarHeight.
Just reused the getBarCount function from your example.
Chart.defaults.groupableHBar = Chart.helpers.clone(Chart.defaults.horizontalBar);
Chart.controllers.groupableHBar = Chart.controllers.horizontalBar.extend({
calculateBarY: function(index, datasetIndex, ruler) {
var me = this;
var meta = me.getMeta();
var yScale = me.getScaleForId(meta.yAxisID);
var barIndex = me.getBarIndex(datasetIndex);
var topTick = yScale.getPixelForValue(null, index, datasetIndex, me.chart.isCombo);
topTick -= me.chart.isCombo ? (ruler.tickHeight / 2) : 0;
var stackIndex = this.getMeta().stackIndex;
if (yScale.options.stacked) {
if(ruler.datasetCount>1) {
var spBar=ruler.categorySpacing/ruler.datasetCount;
var h=me.calculateBarHeight(ruler);
return topTick + (((ruler.categoryHeight - h) / 2)+ruler.categorySpacing-spBar/2)+(h+spBar)*stackIndex;
}
return topTick + (ruler.categoryHeight / 2) + ruler.categorySpacing;
}
return topTick +
(ruler.barHeight / 2) +
ruler.categorySpacing +
(ruler.barHeight * barIndex) +
(ruler.barSpacing / 2) +
(ruler.barSpacing * barIndex);
},
calculateBarHeight: function(ruler) {
var returned=0;
var me = this;
var yScale = me.getScaleForId(me.getMeta().yAxisID);
if (yScale.options.barThickness) {
returned = yScale.options.barThickness;
}
else {
returned= yScale.options.stacked ? ruler.categoryHeight : ruler.barHeight;
}
if(ruler.datasetCount>1) {
returned=returned/ruler.datasetCount;
}
return returned;
},
getBarCount: function () {
var stacks = [];
// put the stack index in the dataset meta
Chart.helpers.each(this.chart.data.datasets, function (dataset, datasetIndex) {
var meta = this.chart.getDatasetMeta(datasetIndex);
if (meta.bar && this.chart.isDatasetVisible(datasetIndex)) {
var stackIndex = stacks.indexOf(dataset.stack);
if (stackIndex === -1) {
stackIndex = stacks.length;
stacks.push(dataset.stack);
}
meta.stackIndex = stackIndex;
}
}, this);
this.getMeta().stacks = stacks;
return stacks.length;
}
});
var data = {
labels: ["January", "February", "March"],
datasets: [
{
label: "Dogs",
backgroundColor: "rgba(255,0,0,0.2)",
data: [20, 10, 25],
stack: 1,
xAxisID: 'x-axis-0',
yAxisID: 'y-axis-0'
},
{
label: "Cats",
backgroundColor: "rgba(255,255,0,0.2)",
data: [70, 85, 65],
stack: 1,
xAxisID: 'x-axis-0',
yAxisID: 'y-axis-0'
},
{
label: "Birds",
backgroundColor: "rgba(0,255,255,0.2)",
data: [10, 5, 10],
stack: 1,
xAxisID: 'x-axis-0',
yAxisID: 'y-axis-0'
},
{
label: ":-)",
backgroundColor: "rgba(0,255,0,0.2)",
data: [20, 10, 30],
stack: 2,
xAxisID: 'x-axis-1',
yAxisID: 'y-axis-0'
},
{
label: ":-|",
backgroundColor: "rgba(0,0,255,0.2)",
data: [40, 50, 20],
stack: 2,
xAxisID: 'x-axis-1',
yAxisID: 'y-axis-0'
},
{
label: ":-(",
backgroundColor: "rgba(0,0,0,0.2)",
data: [60, 20, 20],
stack: 2,
xAxisID: 'x-axis-1',
yAxisID: 'y-axis-0'
},
]
};
var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, {
type: 'groupableHBar',
data: data,
options: {
scales: {
yAxes: [{
stacked: true,
type: 'category',
id: 'y-axis-0'
}],
xAxes: [{
stacked: true,
type: 'linear',
ticks: {
beginAtZero:true
},
gridLines: {
display: false,
drawTicks: true,
},
id: 'x-axis-0'
},
{
stacked: true,
position: 'top',
type: 'linear',
ticks: {
beginAtZero:true
},
id: 'x-axis-1',
gridLines: {
display: true,
drawTicks: true,
},
display: false
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
<canvas id="myChart"></canvas>
Also put example on jsfiddle here: https://jsfiddle.net/b7gnron7/4/
Code is not strongly tested, you might found some bugs especially if you try to display only one stacked group (use horizontalBar instead in this case).
Your post is a little bit old... not sure that you still need a solution, but it could be useful for others ^_^

How to display Labels on Doughnut chart in Chart.js

I want to know how I would be able to show Labels on the doughnut chart and the legend, I'm using chart.js as plugin
I used scaleShowLabels: true but It doesn't work
here is my code :
var data = [{
value: 30,
color: "#F7464A",
label: "Yasser"
}, {
value: 50,
color: "#E2EAE9",
label: "Zeyd"
}, {
value: 100,
color: "#D4CCC5",
label: "Mouad"
}, {
value: 40,
color: "#949FB1",
label: "Hanine"
}, {
value: 120,
color: "#4D5360",
label: "Kheira"
}
]
var options = {
animation: false,
scaleShowLabels: true
};
//Get the context of the canvas element we want to select
var c = $('#myChart');
var ct = c.get(0).getContext('2d');
var ctx = document.getElementById("myChart").getContext("2d");
/*************************************************************************/
myNewChart = new Chart(ct).Doughnut(data, options);
DEMO + CODE
I found all the solutions of the Chart js main problems,
it's about an edited js file, which has all code samples, you can find more information about it here :
https://github.com/FVANCOP/ChartNew.js

Categories