I'm trying to create a bar chart using Chart.js. I'm trying to have the chart display bars above one going upward, whereas values below 1 (e.g. 0.8) point downward. The same as the chart would be displayed if it contained values below zero. Essentially I'm trying to change the base line to 1 rather than 0 for the Y-axis.
Something like this:
The best way to do this (and obviously more work) would be to create a custom axes. Chart.js explains how to do this here:
https://www.chartjs.org/docs/latest/developers/axes.html
I've also create a fiddle where the datavalues are modified by a set baseline. I've modified the tooltip and y-axis label as well so that everything shows based on the baseline. It's not as elegant as a custom axis, but it's quick and gets the job done (assuming the baseline is known). You can check out the fiddle here:
https://jsfiddle.net/tkngc02h/1/
And, in case you just want to see the code, here it is:
<!doctype html>
<html>
<head>
<title>Line Styles</title>
<script src="https://www.chartjs.org/dist/2.9.3/Chart.min.js"></script>
<script src="https://www.chartjs.org/samples/latest/utils.js"></script>
<style>
canvas{
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<div style="width:75%;">
<canvas id="canvas"></canvas>
</div>
<script>
var baseline = 1;
var config = {
type: 'bar',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'TestData',
fill: false,
backgroundColor: window.chartColors.blue,
borderColor: window.chartColors.blue,
data: [
0 - baseline,
1.8 - baseline,
2.1 - baseline,
-0.2 - baseline,
1.3 - baseline,
-0.5 - baseline,
-0.23 - baseline,
0 - baseline
],
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js Line Chart',
},
tooltips: {
mode: 'index',
intersect: false,
callbacks: {
// Use the footer callback to display the sum of the items showing in the tooltip
label: function(tooltipItem, data) {
var label = data.datasets[tooltipItem.datasetIndex].label || '';
if (label) {
label += ': ';
}
label += tooltipItem.yLabel + baseline;
return label;
},
},
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Month'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Value',
},
ticks: {
// Include a dollar sign in the ticks
callback: function(value, index, values) {
return value + baseline;
}
}
}]
}
}
};
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myLine = new Chart(ctx, config);
};
</script>
</body>
</html>
Related
I need after each value to be a percent symbol ( % ) For example: 12% instead of 12
The below code in write in laravel php for the chartpie.
<script src="{{asset('assets/admin/js/vendor/apexcharts.min.js')}}"></script>
<script src="{{asset('assets/admin/js/vendor/chart.js.2.8.0.js')}}"></script>
<script>
var ctx = document.getElementById('tokenomi');
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels:<?=$label?>,
datasets: [{
data:<?=$values?>,
],
borderColor: [
'rgba(231, 80, 90, 0.75)'
],
borderWidth: 0,
}]
},
options: {
aspectRatio: 1,
responsive: true,
maintainAspectRatio: true,
elements: {
line: {
tension: 0 // disables bezier curves
}
},
scales: {
xAxes: [{
display: false
}],
yAxes: [{
display: false
}]
},
legend: {
display: false,
}
}
});
</script>
Check the current chart pie below, I tried a lot but I can't find a solution.
How do I add percent sign (%) behind of all values
Thanks
You need to define a tooltips.callback.label function as shown below. For further details please consult Chart.js v. 2.8.0 documentation here.
options: {
...
tooltips: {
callbacks: {
label: (tooltipItem, data) => data.datasets[0].data[tooltipItem.index] + '%'
}
},
...
Please note that you're using a rather old version of Chart.js, the today latest stable version is 3.7.0.
I'm using the HorizontalBar option of the Chartjs plugin and I have values between -15 and 115. When my percentage value is 0.75 I'd like the bar to fill from -15 to 0.75.
I have set the properties beginAtZero false (which I believe it only works in Y axis..) and fill as true but it does not work.
datasets: [
{
data: [percentage],
fill: true,
backgroundColor: 'rgba(0, 0, 0, 1)'
}]
....
options:
{
scales:
{
xAxes: [
{
ticks:
{
beginAtZero: false,
min: min,
max: max
}
}],
}
}
As you may see in this JSFiddle the black bar starts at 0 and should start at -15.
This can be done with a floating bar since Chart.js v2.9.0, a feature that was merged into chartjs:master with pull request #6056. Individual bars can now be specified with the syntax [min, max].
<html>
<head>
<title>Floating Bar</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<div>
<canvas id="canvas" height="50"></canvas>
</div>
<script>
var percentage = 0.92;
var min = -15;
var max = 115;
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'horizontalBar',
data: {
datasets: [{
data: [[min, percentage]],
fill: true,
backgroundColor: 'rgba(0, 0, 0, 1)'
}]
},
options: {
title: {
display: false
},
tooltips: {
mode: 'index',
intersect: false
},
legend: {
display: false
},
responsive: true,
scales: {
xAxes: [{
ticks: {
min: min,
max: max
}
}],
}
}
});
};
</script>
</body>
</html>
I am trying to draw a graph, but the left and the bottom corners keep getting this blank margin. How do I get rid of that? I managed to erase them, but at the same time it erases the gridLines for the X axis. I want to keep the Xaxis gridlines.
Notice that I also want that border around the graph. Didn't find a way to draw the border using the chart.js.
The white spaces are very evidient, right on the bottom and on the left, spacing the gray border away. You can see it on the image:
I tried disabling the ticks display.
My chart so far:
var myChart = new Chart(modalChart, {
type: 'bar',
data: {
labels: ['Total enviado', 'Total recebido', 'total aberto', 'total convertido'],
datasets: [{
backgroundColor: my_gradient,
data: [totalEnviado,totalRecebido, totalAberto,totalConvertido]
}]
},
options: {
legendCallback: function(chart){
var text = [];
text.push('<div class = "modal-graph-container">');
text.push('<div class = "modal-graph-inner">');
for (var i=0; i<chart.data.labels.length; i++) {
console.log(chart.data.datasets[i]); // see what's inside the obj.
text.push('<div class = "modal-graph-child">');
text.push('<span style="">' + chart.data.labels[i] + '</span>');
console.log(chart.data.labels[i]);
text.push('</div>');
}
text.push('</div>');
text.push('</div>');
return text.join("");
},
legend: {
display:false
},
scales: {
xAxes:[{
display: true,
categoryPercentage:1.0,
barPercentage:1.0,
ticks: {
beginAtZero: true,
display:false
}
}],
yAxes: [{
ticks: {
beginAtZero:true,
display: false
},
gridLines:{
display:false
}
}]
}
}
});
Notice that I also want that border around the graph. Didn't find a way to draw the border using the chart.js only. This gray border around the graph and the gray borders separating the bars are very important.
You need to set the drawTicks option to false for both the x- and y-axis:
gridLines: {
drawTicks: false
}
Working example:
var modalChart = document.getElementById("chart"),
totalEnviado = 4,
totalRecebido = 3,
totalAberto = 2,
totalConvertido = 1,
my_gradient = "orange";
// --
var myChart = new Chart(modalChart, {
type: 'bar',
data: {
labels: ['Total enviado', 'Total recebido', 'total aberto', 'total convertido'],
datasets: [{
backgroundColor: my_gradient,
data: [totalEnviado, totalRecebido, totalAberto, totalConvertido]
}]
},
options: {
legendCallback: function(chart) {
var text = [];
text.push('<div class = "modal-graph-container">');
text.push('<div class = "modal-graph-inner">');
for (var i = 0; i < chart.data.labels.length; i++) {
console.log(chart.data.datasets[i]); // see what's inside the obj.
text.push('<div class = "modal-graph-child">');
text.push('<span style="">' + chart.data.labels[i] + '</span>');
console.log(chart.data.labels[i]);
text.push('</div>');
}
text.push('</div>');
text.push('</div>');
return text.join("");
},
legend: {
display: false
},
scales: {
xAxes: [{
display: true,
categoryPercentage: 1.0,
barPercentage: 1.0,
ticks: {
beginAtZero: true,
display: false
},
gridLines: {
drawTicks: false
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
display: false
},
gridLines: {
display: false,
drawTicks: false
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<div style="border:1px solid #000">
<canvas id="chart"></canvas>
</div>
I am creating a stacked bar chart using Chart.js. However, I cannot find in the documentation how to change some things.
How to add a label on the Y axis.
How to shorten the label on the X axis so it displays only
the first 10 letters.
How to reverse the order in which the values are shown in
the tooltip.
Are these thigs are possible to implement?
I have marked what I want to change here.
Here are what my chart options look like now:
var ctx = $("#newchart");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: {
barValueSpacing: 20,
tooltips: {
enable: true,
mode: 'label',
callbacks: {
label: function(tooltipItem, data){
var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || '';
return datasetLabel + ': ' + Number(tooltipItem.yLabel) + ' Users';
}
}
},
responsive: true,
segmentShowStroke: true,
scales: {
xAxes: [{
display: false,
stacked: true,
ticks:{
stepSize : 10,
},
gridLines: {
lineWidth: 0,
color: "#9E9E9E"
}
}],
yAxes: [{
stacked: true,
ticks: {
min: 0,
stepSize: 10,
},
gridLines: {
lineWidth: 0,
color: "#9E9E9E"
}
}]
}
}
});
1. Adding a Y-axis label
in the yAxes object give it a scaleLabel object that takes in labelString (example fiddle)
yAxes: [{
scaleLabel: {
labelString: 'Value'
}
}]
2. Shortening xAxis category labels
For this, you can pass a userCallback function to the xAxis ticks object that can return your desired output. The function will take in the original label in its first parameter so you can just return a substring at your desired length, example fiddle
xAxes: [{
ticks: {
userCallback: function(label, index, labels) {
if(typeof label === "string")
{
return label.substring(0,1)
}
return label;
},
}
}],
3. reverse tooltip order
The tooltips object accepts a function called itemSort that can be passed to Array.prototype.sort.
So you could so something like below, but you may also need to compare the objects index as well as the datasetIndex to get your desired result. (example fiddle)
tooltips: {
mode: 'label',
itemSort: function(a, b) {
return b.datasetIndex - a.datasetIndex
},
},
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 months ago.
Improve this question
I want to paint a horizontal bar with Chart.js, but i want a default background color (Which is the max value) and paint the current value with another color. Just like the image below. How can i do this?
There is no easy way to do this in Chart.js (such as a specific "100% stacked bar" type). What you need is two stacked horizontal bars.
First, define your chart-type as a horizontalBar
// html
<canvas id="chart" height="20"></canvas>
// javascript
var ctx = document.getElementById('chart');
var bar_chart = new Chart(ctx, {
type: 'horizontalBar' // this will give you a horizontal bar.
// ...
};
In order to have a single bar instead of two, they need to be stacked. You also need to hide the scales. Optionally, you can hide the legend and the tooltip. This is all configured in the options:
var bar_chart = new Chart(ctx, {
// ...
options: {
legend: {
display: false // hides the legend
},
tooltips: {
enabled: false // hides the tooltip.
}
scales: {
xAxes: [{
display: false, // hides the horizontal scale
stacked: true // stacks the bars on the x axis
}],
yAxes: [{
display: false, // hides the vertical scale
stacked: true // stacks the bars on the y axis
}]
}
}
};
As stacked bars are placed on top of each other, your first dataset contains your value (57.866), and the second dataset corresponds to max - value. Here's an example considering value = 57866 and max = 80000:
var value = 57866; // your value
var max = 80000; // the max
var bar_chart = new Chart(ctx, {
// ...
datasets: [{
data: [value],
backgroundColor: "rgba(51,230,125,1)"
}, {
data: [max - value],
backgroundColor: "lightgrey"
}]
};
Here's the jsfiddle with the full code.
In addition to #Tarek's answer,
If you need to get the percentage value in the bar,
https://jsfiddle.net/akshaykarajgikar/bk04frdn/53/
Dependensies:
https://www.chartjs.org/
https://chartjs-plugin-datalabels.netlify.app/
var bar_ctx = document.getElementById('bar-chart');
var bar_chart = new Chart(bar_ctx, {
type: 'horizontalBar',
data: {
labels: [],
datasets: [{
data: [57.866],
backgroundColor: "#00BC43",
datalabels: {
color: 'white' //Color for percentage value
}
}, {
data: [100 - 57.866],
backgroundColor: "lightgrey",
hoverBackgroundColor: "lightgrey",
datalabels: {
color: 'lightgray' // Make the color of the second bar percentage value same as the color of the bar
}
}, ]
},
options: {
legend: {
display: false
},
tooltips: {
enabled: false
},
scales: {
xAxes: [{
display: false,
stacked: true
}],
yAxes: [{
display: false,
stacked: true
}],
}, // scales
plugins: { // PROVIDE PLUGINS where you can specify custom style
datalabels: {
align: "start",
anchor: "end",
backgroundColor: null,
borderColor: null,
borderRadius: 4,
borderWidth: 1,
font: {
size: 20,
weight: "bold", //Provide Font family for fancier look
},
offset: 10,
formatter: function(value, context) {
return context.chart.data.labels[context.dataIndex]; //Provide value of the percentage manually or through data
},
},
},
}, // options
});
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#0.7.0"></script>
<canvas id="bar-chart" height="20"></canvas>