How to show different tooltips on charts (in columns)? - javascript

How to display different tooltips on chart columns? It is necessary to output data from:
data: [220, 315, 380, 470, 520] and data: [135, 190, 180, 160, 240]
Now duplicated.
Here is my code (using chart.js):
My fiddle
https://jsfiddle.net/ebgaouv8/
Thanks in advance for any help!

You have to change your tooltip mode from label to point and dont hard code the datasetIndex. To solve deprecation issue, remove the barpercentage from the scale option and specify it in every dataset or you can configure it globally before you make the chart like this: Chart.defaults.global.datasets.bar.barPercentage = 0.5;.
var barChart = {
labels: ["2016", "2017", "2018", "2019", "2020"],
datasets: [{
label: '',
backgroundColor: "rgba(34,42,171, 0.7)",
borderColor: 'rgba(34,42,171, 1)',
borderWidth: 1,
barPercentage: 0.5,
data: [220, 315, 380, 470, 520]
},
{
label: '',
backgroundColor: "#ceb947",
barPercentage: 0.5,
data: [135, 190, 180, 160, 240]
},
]
};
var ctx4 = document.getElementById("chartJSContainer").getContext("2d");
window.newBar = new Chart(ctx4, {
type: 'bar',
data: barChart,
options: {
title: {
display: false,
fontStyle: 'bold',
text: "Figure"
},
legend: {
display: false,
position: "bottom",
padding: 20,
labels: {}
},
tooltips: {
mode: 'point',
bodySpacing: 10,
cornerRadius: 0,
titleFontSize: 16,
bodyFontSize: 14,
titleMarginBottom: 15,
callbacks: {
label: function(tooltipItem, data) {
var value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
value = value.toString();
value = value.split((/(?=(?:..)?$)/));
value = value.join(',');
return 'Total: ' + value + ' %';
}
}
},
scales: {
xAxes: [{
gridLines: false,
ticks: {
fontColor: 'rgb(37,39,103)',
fontSize: '14',
autoSkip: false,
maxRotation: 45,
minRotation: 45,
padding: 15
}
}],
yAxes: [{
ticks: {
fontColor: 'rgb(37,39,103)',
fontSize: '14',
beginAtZero: true,
stepSize: 100,
userCallback: function(value, index, values) {
value = value.toString();
value = value.split(/(?=(?:..)?$)/);
value = value.join(',');
return value + ' %';
}
}
}]
},
responsive: true,
}
});
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
</body>

Related

Is there a property in for ChartJS that allows you to align bars to the left?

I am trying to create a bar chart with the columns aligned to the left using the PrimeNg p-chart. I started with the stacked graph on http://primefaces.org/primeng/chart/bar.
This is my current graph:
Desired look:
I have tried using categoryPercentage: 0.99, and barPercentage: 1.0 from How to align ChartJS bars to the left?. These didn't create my desired look as they expanded the column to the full width. I want to have smaller width columns and shift them over to the left. Are there any properties that can be used to achieve this effect? Are there any alternatives to ChartJS properties?
this.stackedData =
[{
type: 'bar',
categoryPercentage: 0.25,
borderRadius: 3,
label: '200',
backgroundColor: '#003D79',
data: [
50,
55,
78,
48,
90,
76,
42
]
}, {
type: 'bar',
categoryPercentage: 0.25,
borderRadius: 3,
label: '400',
backgroundColor: '#AC0000',
data: [
21,
4,
24,
75,
37,
65,
34
]
}, {
type: 'bar',
categoryPercentage: 0.25,
borderRadius: 3,
label: '401',
backgroundColor: '#E80000',
data: [
41,
0,
24,
74,
23,
21,
32
]
}, {
type: 'bar',
categoryPercentage: 0.25,
borderRadius: 3,
label: '402',
backgroundColor: '#5C0000',
data: [
41,
52,
0,
74,
23,
21,
32
]
}, {
type: 'bar',
categoryPercentage: 0.25,
borderRadius: 3,
label: 'Other',
backgroundColor: '#D5D5D5 ',
data: [
]
}];
this.stackedOptions = {
plugins: {
tooltips: {
mode: 'index',
intersect: false
},
legend: {
position: 'bottom',
align: 'end',
labels: {
usePointStyle: 'circle',
}
},
},
scales: {
x: {
stacked: true,
grid: {
display: false
},
ticks: {
maxRotation: -45,
minRotation: -45,
padding: 30,
}
},
y: {
stacked: true,
grid: {
drawBorder: false,
lineWidth: 0.5,
}
}
}
};

How to set labels align left in Horizontal Bar using chart.js?

My code using chart.js
var ctx_1 = document.getElementById('non_200_pages').getContext('2d');
var myChart_1 = new Chart(ctx_1, {
type: 'horizontalBar',
data: {
labels: ["Total","301 Redirect","Broken Pages (4xx Errors)","Uncategorised HTTP Response Codes","5xx Errors","Unauthorised Pages","Non-301 Redirects"],
datasets: [{
data: [ {{ $array_non_200_pages[0] }}, {{ $array_non_200_pages[1] }}, {{ $array_non_200_pages[2] }}, {{ $array_non_200_pages[3] }}, {{ $array_non_200_pages[4] }}, {{ $array_non_200_pages[5] }}, {{ $array_non_200_pages[6]}} ],
backgroundColor: [
'rgba(237, 56, 98, 1.0)',
'rgba(237, 56, 98, 1.0)',
'rgba(237, 56, 98, 1.0)',
'rgba(237, 56, 98, 1.0)',
'rgba(237, 56, 98, 1.0)',
'rgba(237, 56, 98, 1.0)',
'rgba(237, 56, 98, 1.0)'
]
}]
},
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:5,
display: false
},
gridLines: {
drawBorder: false,
}
}],
},
plugins: {
datalabels: {
align: 'end',
anchor: 'end',
backgroundColor: function(context) {
return context.dataset.backgroundColor;
},
borderRadius: 4,
color: 'white',
formatter: Math.round
}
}
}
});
My work
Expected Output
I'm having a problem on how to set the labels text align to left. What I want to do is I want my label same with the next picture but I don't know where in Options:{ settings for text align. Is there anyone can help me how to fix it? I can't find any on the https://www.chartjs.org/docs/latest/configuration/legend.html. Thank you in advance.
The yAxis.ticks labels can be left aligned by defining mirror: true combined with adding some padding.
yAxes: [{
ticks: {
mirror: true,
padding: 220
},
To make the labels visible on the chart area, the same padding needs to be defined left of the chart layout.
layout: {
padding: {
left: 220
}
},
Please have a look at your changed code below.
new Chart('myChart', {
type: 'horizontalBar',
data: {
labels: ["Total", "301 Redirect", "Broken Pages (4xx Errors)", "Uncategorised HTTP Response Codes", "5xx Errors", "Unauthorised Pages", "Non-301 Redirects"],
datasets: [{
data: [16, 14, 1, 1, 0, 0, 0],
backgroundColor: ['rgba(237, 56, 98, 1.0)', 'rgba(237, 56, 98, 1.0)', 'rgba(237, 56, 98, 1.0)', 'rgba(237, 56, 98, 1.0)', 'rgba(237, 56, 98, 1.0)', 'rgba(237, 56, 98, 1.0)','rgba(237, 56, 98, 1.0)']
}]
},
options: {
responsive: false,
layout: {
padding: {
left: 220
}
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
mirror: true,
padding: 220
},
gridLines: {
display: false
},
}],
xAxes: [{
ticks: {
display: false
},
gridLines: {
drawBorder: false,
}
}],
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" width="500" height="200"></canvas>
You can control labels alignment by using crossAlignment option on the tick configuration. There are three possible values: "near", "center", and "far".
In your case, you will just use near
options: {
...
scales: {
y: {
ticks: {
crossAlign: "far",
},
},
},
}

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
}
}
}
});

Chart.js smooth draw line animation

I want to make Chart.js line graph to draw line from left to right smoothly. I want alson icon at the end of line.
So far I was able to make line, but transition is very harsh. It is really basic way, just adding new datapoints to graph. Could somebody please help me to fix it?
Thank you
here is codepen: https://codepen.io/anon/pen/OwYGrp?editors=0010
code:
const datam = [510, 13357, 19950, 26679, 32514, 37720, 44487, 50596, 56095, 50000, 40670]
var noneimg = new Image();
noneimg.src = 'https://upload.wikimedia.org/wikipedia/commons/8/8c/Transparent.png'
var sun = new Image();
sun.src = 'https://i.imgur.com/yDYW1I7.png';
function animation (u) {
function animatePart(u) {
myChart.data.datasets[0].data.push(datam[u]);
Chart.pluginService.register({
afterUpdate: function(chart) {
if (u>0 && u <datam.length) {
myChart.config.data.datasets[0]._meta[0].data[u-1]._model.pointStyle = noneimg;
}
myChart.config.data.datasets[0]._meta[0].data[u]._model.pointStyle = sun;
}
});
myChart.update();
}
for (let i = 0; i<=datam.length; i++) {
(function() {
setTimeout(function () { animatePart(i); }, 200+ ( i * 580 ));
})()}
}
var ctx = document.getElementById("line_chart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017" ],
datasets: [{
label: 'xxxx xx',
radius: 0.7,
fill: '#FFFFFF',
data: [],
backgroundColor: 'dodgerblue',
borderColor: 'dodgerblue',
borderWidth: 4,
},{
label: 'xxxx',
fill: '#FFFFFF',
radius: 0.7,
data: [],
backgroundColor: 'indianred',
borderColor: 'indianred',
borderWidth: 5
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
title: {
display: true,
text: 'xxx',
fontSize: 24,
fontFamily: "open sans",
fontColor: 'black',
fontStyle: 'bold',
},
legend: {
labels: {
fontColor: 'black',
fontSize: 16,
}},
tooltips: {
mode: 'index',
intersect: false,
backgroundColor: 'black',
titleFontColor: 'white',
titleFontSize: 16,
bodyFontSize: 13,
bodyFontColor: 'white',
bodySpacing: 3,
yPadding: 8,
borderColor: 'black',
},
hover: {
mode: 'nearest',
},
animation: {
duration: 1600,
numSteps: 10,
easing: "easeInQuad",
},
scales: {
xAxes: [{
ticks: {
fontColor: 'black',
fontSize: 16,
},
display: true,
scaleLabel: {
display: false,
labelString: 'xxx'
}
}],
yAxes: [{
ticks: {
min: 0,
max: 70000,
beginAtZero: false,
fontColor: 'black',
fontSize: 16,
},
display: true,
scaleLabel: {
display: false,
labelString: 'xx'
}
}]
},
}
})
animation()

Hide first label in legend in a Chart using chart.js

I have created a stacked bar chart and i have to hide first dataset's label and its box in legend which is "Total Line", Is there anyway to hide first or any dataset's label. i have read the documentation there is a filter in options but it didn't work.
Hiding This label
Here is the html and js for chart
var ctx = document.getElementById("girth-measure-chart");
var totalLine = [115, 118, 88, 93, 103, 118, 125]
var total = [112, 115, 85, 90, 100, 115, 122]
var arms = [46, 55, 41, 41, 47, 54, 57]
var neck = [17, 20, 15, 15, 17, 20, 21]
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep"],
datasets: [{
type: 'line',
label: 'Total Line',
data: totalLine,
fill: false,
borderColor: ["#ff7899"],
legend: false,
pointBackgroundColor: "#ff151f",
pointRadius: 8,
pointHoverRadius: 8,
pointHoverBackgroundColor: "#990e14",
pointHoverBorderColor: "#6754d3"
}, {
type: 'bar',
label: 'Neck',
data: neck,
backgroundColor: "#e99449",
hoverBackgroundColor: "#d36d14"
}, {
type: 'bar',
label: 'Arms',
data: arms,
backgroundColor: "#49bae9",
hoverBackgroundColor: "#0789bf"
}, {
type: 'bar',
label: 'Total',
data: total,
backgroundColor: "#6754d3",
hoverBackgroundColor: "#260cbd"
}
]
},
options: {
legend: {
display: true,
labels: {
display: true,
boxWidth: 12,
}
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
gridLines: {
display: false
},
barThickness: 25,
ticks: {
display: true,
fontFamily: "Montserrat",
fontColor: "#2c405a",
fontSize: 12
}
}],
yAxes: [{
gridLines: {
display: false
},
ticks: {
display: false,
stepSize: 10,
min: 0,
max: 150,
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.js"></script>
<div class="chart-container">
<div class="girth-measure-chart-inner" style="width: 100%;">
<canvas id="girth-measure-chart" height=""></canvas>
</div>
</div>
Use the filter method under options.
options: {
legend: {
labels: {
filter: function(legendItem, chartData) {
// return true or false based on legendItem's datasetIndex (legendItem.datasetIndex)
}
}
}
}
In your case return false for the first index and true for the rest.
var ctx = document.getElementById("girth-measure-chart");
var totalLine = [115, 118, 88, 93, 103, 118, 125]
var total = [112, 115, 85, 90, 100, 115, 122]
var arms = [46, 55, 41, 41, 47, 54, 57]
var neck = [17, 20, 15, 15, 17, 20, 21]
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep"],
datasets: [{
type: 'line',
label: 'Total Line',
data: totalLine,
fill: false,
borderColor: ["#ff7899"],
legend: false,
pointBackgroundColor: "#ff151f",
pointRadius: 8,
pointHoverRadius: 8,
pointHoverBackgroundColor: "#990e14",
pointHoverBorderColor: "#6754d3"
}, {
type: 'bar',
label: 'Neck',
data: neck,
backgroundColor: "#e99449",
hoverBackgroundColor: "#d36d14"
}, {
type: 'bar',
label: 'Arms',
data: arms,
backgroundColor: "#49bae9",
hoverBackgroundColor: "#0789bf"
}, {
type: 'bar',
label: 'Total',
data: total,
backgroundColor: "#6754d3",
hoverBackgroundColor: "#260cbd"
}
]
},
options: {
legend: {
labels: {
filter: function(legendItem, chartData) {
if (legendItem.datasetIndex === 0) {
return false;
}
return true;
}
}
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
gridLines: {
display: false
},
barThickness: 25,
ticks: {
display: true,
fontFamily: "Montserrat",
fontColor: "#2c405a",
fontSize: 12
}
}],
yAxes: [{
gridLines: {
display: false
},
ticks: {
display: false,
stepSize: 10,
min: 0,
max: 150,
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.js"></script>
<div class="chart-container">
<div class="girth-measure-chart-inner" style="width: 100%;">
<canvas id="girth-measure-chart" height=""></canvas>
</div>
</div>

Categories

Resources