How do remove the bottom scale on a Chart.js bar chart - javascript

I'm using Chart.js to create the following chart:
The issue is that I want to make the scale at the bottom only show 0 and the maximum number (here being 12).
JavaScript:
<script>
new Chart(document.getElementById("leads-bar"), {
type: 'horizontalBar',
data: {
labels: ["Hot", "Warm", "Cold"],
datasets: [
{
backgroundColor: ["#d23232", "#ff9347", "#bbbbbb"],
data: [7, 9, 11]
}
]
},
options: {
legend: {
display: false
},
tooltips: {
display: false
},
title: {
display: false
},
scales: {
xAxes: [{
stacked: true,
gridLines: {
display: false,
drawBorder: false,
},
scaleShowLabels: false,
}],
yAxes: [{
stacked: false,
gridLines: {
color: ["#eeeeee"]
}
}]
}
}
});

var dataArr = [154.23, 203.21, 429.01, 637.41];
var chart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: [154.23, 203.21, 429.01, 637.41],
datasets: [{
label: 'LINE',
data: dataArr,
backgroundColor: 'rgba(0, 119, 290, 0.2)',
borderColor: 'rgba(0, 119, 290, 0.6)',
fill: false,
tension: 0
}]
},
options: {
scales: {
xAxes: [{
ticks: {
min: Math.min.apply(this, dataArr),
max: Math.max.apply(this, dataArr),
callback: function(value, index, values) {
if (index === values.length - 1) return Math.min.apply(this, dataArr);
else if (index === 0) return Math.max.apply(this, dataArr);
else return '';
}
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>

Related

How to align vertical axis area on two charts in chart.js

in chart.js I'd like to have 2 charts (one under another) with ticks syncronized. Currently it looks so
as you can see dates are not aligned. Setting equal min-max values is impossible here since values are too different.
I think the solution would be to set equal width to both y-axes. The case is complicated by the second y-axes in upper chart, but may be it's possible to place an empty right scale on the bottom chart?
My current options for the top chart are
options: {
tooltips: {
enabled: true,
trigger: 'axis',
intersect: false,
mode : 'index'
},
responsive: true,
maintainAspectRatio: false,
layout: {
padding: {
// left: 500,
right: 0,
top: 0,
bottom: 0,
},
},
scales: {
xAxes: [
{
boundaryGap : false,
gridLines: {
display: false,
},
ticks: {
// Include a dollar sign in the ticks
callback: function(value, index, values) {
return value.split('.').slice(0,2).join('.');
}
},
},
],
yAxes: [
{
id: keys[0],
position: "left",
gridLines: {
drawBorder: false,
zeroLineColor: "rgba(147, 147, 147, 0.2)",
color: "rgba(147, 147, 147, 0.2)",
},
ticks: {
padding: 20,
fontColor: "#2C71C3",
beginAtZero: false,
},
}, {
id: keys[1],
position: "right",
gridLines: {
drawBorder: false,
color: "rgba(147, 147, 147, 0)",
},
ticks: {
padding: 20,
fontColor: "#C6C6C6",
beginAtZero: false,
},
},
],
},
and for the bottom one
options: {
tooltips: {
enabled: true,
trigger: 'axis',
intersect: false,
mode : 'index'
},
responsive: true,
maintainAspectRatio: false,
layout: {
padding: {
// left: 500,
right: 0,
top: 0,
bottom: 0,
},
},
scales: {
yAxes: [
{
ticks: {
reverse: true,
},
},
],
xAxes: [
{
gridLines: {
display: false,
},
ticks: {
// Include a dollar sign in the ticks
callback: function(value, index, values) {
return value.split('.').slice(0,2).join('.');
}
},
},
],
},
I dont know how to or if it is even possible to define a width for a scale, but what you can do is add a second Y axis on the right with the grid dissabled and the callback returning a few spaces for spacing
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
scales: {
yAxes: [{
position: 'left'
},
{
position: 'right',
gridLines: {
display: false
},
ticks: {
callback: () => (' ')
}
}
]
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>
Little late to the party, but it is possible to set a fixed width. I updated #LeeLenalee snippet with an example (both y axis have a 100px width in this case). This way, it is possible to align both graphs without any problem. Make sure to set a width that isn't too small for the labels though!
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
scales: {
yAxes: [{
position: 'left',
afterFit: (scaleInstance) => scaleInstance.width = 100,
},
{
position: 'right',
afterFit: (scaleInstance) => scaleInstance.width = 100,
gridLines: {
display: false
},
ticks: {
callback: () => ''
}
}
]
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>

How to reduce number of multiple gridlines in stack bar graph chart.js

I am working on chart.js for implementing stack bar graph. That graph has few issues like
Not showing tick size vertically at left
Showing unwanted horizontal gridlines
Displaying horizontal thick line on top instead of bottom
This is my code
public stackbar()
{
Chart.defaults.global.datasets.bar.barPercentage = 0.5;
Chart.defaults.global.datasets.bar.categoryPercentage = 0.5;
var colors = ['#299DFF','#80FFFF','#F8362B',];
var chBar = document.getElementById("mychart");
var chartData = {
labels: ["Product"],
datasets: [{
label: 'P2',
data: [29566],
backgroundColor: colors[0]
},
{
label: 'P3',
data: [O2],
backgroundColor: colors[1]
},
{
label: 'P4',
data: [3],
backgroundColor: colors[2]
}
]
};
if (chBar) {
new Chart(chBar, {
type: 'bar',
data: chartData,
options: {
scales: {
xAxes: [{
gridLines: {
display:false
},
//barPercentage: 0.5,
//categoryPercentage: 0.5
barPercentage: 0.5,
categoryPercentage: 0.5
}
],
yAxes: [{
gridLines: {
display:true
},
type: 'logarithmic',
ticks: {
beginAtZero: true,
userCallback: (value, index) => {
const remain = value / (Math.pow(10, Math.floor(Chart.helpers.log10(value))));
if (remain == 1 || remain == 2 || remain == 5 || index == 0) {
return value.toLocaleString();
}
return '';
},
suggestedMax: 80,
padding: 25
}
}]
},
legend: {
display: true,
maxWidth: 100,
padding:30,
fullWidth:true,
position: 'bottom',
lineHeight: 12,
justifyContent: 'space-between',
labels: {
fontSize: 10,
usePointStyle: true
}
},
}
});
}
This is the screenshot
How can I fix these issues?
The horizontal grid lines can be removed through the following configuration in the chart options:
yAxes: [{
gridLines: {
display: false
},
I changed this in your code and removed a few unnecessary definitions and it looks just fine to me as you can see in the following runnable code.
var colors = ['#299DFF', '#80FFFF', '#F8362B'];
var chartData = {
labels: ["Product"],
datasets: [{
label: 'P2',
data: [29566],
backgroundColor: colors[0]
},
{
label: 'P3',
data: [2],
backgroundColor: colors[1]
},
{
label: 'P4',
data: [3],
backgroundColor: colors[2]
}
]
};
new Chart('myChart', {
type: 'bar',
data: chartData,
options: {
scales: {
xAxes: [{
barPercentage: 0.5,
categoryPercentage: 0.5
}
],
yAxes: [{
gridLines: {
display: false
},
type: 'logarithmic',
ticks: {
beginAtZero: true,
userCallback: (value, index) => {
const remain = value / (Math.pow(10, Math.floor(Chart.helpers.log10(value))));
if (remain == 1 || remain == 2 || remain == 5 || index == 0) {
return value.toLocaleString();
}
return '';
}
}
}]
},
legend: {
display: true,
maxWidth: 100,
padding: 30,
fullWidth: true,
position: 'bottom',
lineHeight: 12,
justifyContent: 'space-between',
labels: {
fontSize: 10,
usePointStyle: true
}
}
}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<canvas id="myChart" height="150"></canvas>

How to display value after the bar using chart.js

My chart.js
var ctx_1 = document.getElementById('https_http').getContext('2d');
var myChart_1 = new Chart(ctx_1, {
type: 'horizontalBar',
data: {
labels: ['HTTPS Pages','HTTP Pages'],
datasets: [{
data: [ {{ $array_https_http[0] }}, {{ $array_https_http[1] }}],
backgroundColor: [
'rgb(81, 170, 120)',
'rgb(198, 222, 208)'
]
}]
},
options: {
showAllTooltips: true,
tooltips: {
enabled: true,
displayColors: false,
yPadding: 20,
xPadding: 30,
caretSize: 10,
backgroundColor: 'rgba(240, 240, 240, 1)',
bodyFontSize: 16,
bodyFontColor: 'rgb(50, 50, 50)',
borderColor: 'rgba(0,0,0,1)',
borderWidth: 1,
cornerRadius: 0,
yAlign: 'bottom',
xAlign: 'center',
position: 'custom',
custom: function(tooltip) {
if (!tooltip) return;
// disable displaying the color box;
tooltip.displayColors = false;
},
callbacks: {
// use label callback to return the desired label
label: function(tooltipItem, data) {
return tooltipItem.yLabel + " : " + tooltipItem.xLabel ;
},
// remove title
title: function(tooltipItem, data) {
return;
}
}
},
responsive: false,
legend: { display: false },
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
},
gridLines: {
display: false
},
}],
xAxes: [{
ticks: {
stepSize:100
}
}],
}
}
});
My tooltips code
Chart.Tooltip.positioners.custom = function(elements, position) {
if (!elements.length)
return false;
var em = elements[0]._model;
return {
x: em.x-((em.x-em.base)/2),
y: em.y+em.height/4
}
}
My output
My expected output
Is there anyone can help me how to put those value after the bar like the second picture. I just want to display the value to know even its zero. My custom tooltips was to show a different hover rather than default. All your help are appreciated and thank you in advance.
You can use the chartjs.datalabel plugin for achieving the need. I have created a fiddle for you -> http://jsfiddle.net/Labkrpf4/
Hope it helps!
var ctx_1 = document.getElementById('https_http').getContext('2d');
var myChart_1 = new Chart(ctx_1, {
type: 'horizontalBar',
data: {
labels: ['HTTPS Pages', 'HTTP Pages'],
datasets: [{
data: [0, 430],
backgroundColor: [
'rgb(81, 170, 120)',
'rgb(198, 222, 208)'
]
}]
},
options: {
showAllTooltips: true,
tooltips: {
enabled: true,
displayColors: false,
yPadding: 20,
xPadding: 30,
caretSize: 10,
backgroundColor: 'rgba(240, 240, 240, 1)',
bodyFontSize: 16,
bodyFontColor: 'rgb(50, 50, 50)',
borderColor: 'rgba(0,0,0,1)',
borderWidth: 1,
cornerRadius: 0,
yAlign: 'bottom',
xAlign: 'center',
position: 'custom',
custom: function(tooltip) {
if (!tooltip) return;
// disable displaying the color box;
tooltip.displayColors = false;
},
callbacks: {
// use label callback to return the desired label
label: function(tooltipItem, data) {
return tooltipItem.yLabel + " : " + tooltipItem.xLabel;
},
// remove title
title: function(tooltipItem, data) {
return;
}
}
},
responsive: false,
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
},
gridLines: {
display: false
},
}],
xAxes: [{
ticks: {
stepSize: 100
}
}],
},
plugins: {
datalabels: {
align: 'end',
anchor: 'end',
backgroundColor: function(context) {
return context.dataset.backgroundColor;
},
borderRadius: 4,
color: 'white',
formatter: Math.round
}
}
}
});

Is it possible to show labels for all lines?

Basically I have chartJS based line chart, with two lines. X axis has dates, and Y axes has price.
There is two lines (one for average price and one for minimum price).
So I was wondering, if it is at all possible to so that lets say I hover over a point for minimum price, the average price point's label pops up as well, and vice versa.
Or if that is not possible, maybe it is possible to make it so each label contains both values (the min and average price for that particular day).
Here is the code, I have so far:
var ctx = document.getElementById('price-history').getContext('2d');
ctx.height = 150;
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: <?= json_encode($priceChangeData['labels']); ?>,
datasets: [
{
label: 'Minimali kaina',
backgroundColor: 'rgb(64, 127, 178)',
borderColor: 'rgb(64, 127, 178)',
borderWidth: 1,
data: <?= json_encode($priceChangeData['line']['price_min']); ?>,
fill: false
},
{
label: 'Vidutinė kaina',
backgroundColor: '#686868',
borderColor: '#686868',
borderWidth: 1,
data: <?= json_encode($priceChangeData['line']['price_avg']); ?>,
fill: false
}
],
},
options: {
responsive: true,
layout: {
padding: {
left: 20,
right: 15
}
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: false,
labelString: 'Data'
}
}],
yAxes: [{
display: true,
stacked: false,
scaleLabel: {
display: false,
labelString: 'Kaina'
}
}]
}
}
});
I am assuming you are talking about the tooltip­'s label. In that case, you can set tooltips mode to index in your chart­'s options config, like so :
options: {
tooltips: {
mode: 'index'
},
...
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
var ctx = document.getElementById('price-history').getContext('2d');
ctx.height = 150;
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'], //<?= json_encode($priceChangeData['labels']); ?>,
datasets: [{
label: 'Minimali kaina',
backgroundColor: 'rgb(64, 127, 178)',
borderColor: 'rgb(64, 127, 178)',
borderWidth: 1,
data: [3, 1, 4, 2, 5], //<?= json_encode($priceChangeData['line']['price_min']); ?>,
fill: false
}, {
label: 'Vidutinė kaina',
backgroundColor: '#686868',
borderColor: '#686868',
borderWidth: 1,
data: [2, 4, 1, 5, 3], //<?= json_encode($priceChangeData['line']['price_avg']); ?>,
fill: false
}],
},
options: {
responsive: true,
tooltips: {
mode: 'index'
},
layout: {
padding: {
left: 20,
right: 15
}
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: false,
labelString: 'Data'
}
}],
yAxes: [{
display: true,
stacked: false,
scaleLabel: {
display: false,
labelString: 'Kaina'
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>
<canvas id="price-history"></canvas>

Chart.js stacked bar chart in opposite direction

I am trying to achieve something like this using chart.js. I wanted to show data of male/female according to each age group:
Here is my chart options:
var options = {
layout: {
padding: {
top: 5,
}
},
scales:
{
yAxes: [{
display: true,
barPercentage: 0.4,
ticks: {
fontSize: 12
},
stacked: true,
}],
xAxes: [{
stacked: true,
}]
},
responsive: true,
maintainAspectRatio: false,
legend: {
display: false,
},
animation: {
animateScale: true,
animateRotate: true
},
};
var opt = {
type: "horizontalBar",
data: {
labels: ageGroup,
datasets: [{
label: 'Male',
data: maleData,
backgroundColor: '#2196F3',
hoverBackgroundColor: '#2196F3'
},
{
label: 'Female',
data: femaleData,
backgroundColor: '#E91E63',
hoverBackgroundColor: '#E91E63'
}]
},
options: options
};
I changed the positive in femaleData array into a negative number to achieve the result above:
for (var i = 0; i < femaleData.length; i++) {
femaleData[i] = -Math.abs(femaleData[i]);
}
However, the y-axis at 0 is not centralized as it pushed to the right hand side since left hand side got more data. I not even sure if this is the correct way to set the chart in opposite direction. How can I do this correctly?
as per the requirements mentioned in OP­'s comment section
ꜱʜᴏᴡ ᴘᴏꜱɪᴛɪᴠᴇ ᴠᴀʟᴜᴇꜱ ᴏɴ x-ᴀxɪꜱ
use the following callback function for x-axis ticks :
callback: function(t, i) {
return t < 0 ? Math.abs(t) : t;
}
ꜱʜᴏᴡ ᴘᴏꜱɪᴛɪᴠᴇ ᴠᴀʟᴜᴇ ᴏɴ ᴛᴏᴏʟᴛɪᴘ
use the following callback function for tooltips :
callbacks: {
label: function(t, d) {
var datasetLabel = d.datasets[t.datasetIndex].label;
var xLabel = Math.abs(t.xLabel);
return datasetLabel + ': ' + xLabel;
}
}
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
var ageGroup = ['0-10', '11-20', '21-30', '31-40', '41-50', '51-60', '61-70', '71-80', '80+'];
var maleData = [30, 0, 0, 0, 10, 0, 0, 0, 0];
var femaleData = [0, 0, 0, -20, -50, -20, 0, 0, 0];
var options = {
layout: {
padding: {
top: 5,
}
},
scales: {
yAxes: [{
display: true,
barPercentage: 0.4,
ticks: {
fontSize: 12
},
stacked: true,
}],
xAxes: [{
stacked: true,
ticks: {
callback: function(t, i) {
return t < 0 ? Math.abs(t) : t;
}
}
}]
},
tooltips: {
callbacks: {
label: function(t, d) {
var datasetLabel = d.datasets[t.datasetIndex].label;
var xLabel = Math.abs(t.xLabel);
return datasetLabel + ': ' + xLabel;
}
}
},
responsive: true,
//maintainAspectRatio: false,
legend: {
display: false,
},
animation: {
animateScale: true,
animateRotate: true
},
};
var opt = {
type: "horizontalBar",
data: {
labels: ageGroup,
datasets: [{
label: 'Male',
data: maleData,
backgroundColor: '#2196F3',
hoverBackgroundColor: '#2196F3'
}, {
label: 'Female',
data: femaleData,
backgroundColor: '#E91E63',
hoverBackgroundColor: '#E91E63'
}]
},
options: options
};
new Chart(ctx, opt);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>

Categories

Resources