Legends in Chart.js, shows only one label - javascript

Just a warning: I am new to chart.js!
I have a couple of horizontal bar charts and it works fine except one issue that I cannot shake off. I have 5 labels in y-axis but the legend on top of the graph only shows one small rectangle in the color of the first (topmost) bar and even that does not display the label itself, followed by list of labels. I thought it would display each label next to small bar same color as in chart.
Unfortunately, this is an intranet app and I cannot provide a link but here is what I have (data is passed to this function from an ajax call):
function drawRespChart(chartLabels, chartData) {
var ctx = $("#rtChart");
console.log("Labels Array: " + chartLabels);
console.log("Data Array: " + chartData);
if (chartRespTime)
chartRespTime.destroy();
var chart = {
labels: chartLabels,
datasets: [
{
label: chartLabels,
backgroundColor: ["#c45850", "#e8c3b9", "#3cba9f", "#8e5ea2", "#3e95cd"],
data: chartData
}
]
};
chartRespTime = new Chart(ctx, {
type: 'horizontalBar',
data: chart,
datalabels: {
anchor: 'end',
align: 'start',
},
options: {
title: {
display: true,
text: 'IDC Database Response Time (mili-seconds)'
},
legend: {
display: true,
labels: {
fontColor: 'rgb(255, 99, 132)'
}
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Count'
},
ticks: {
major: {
fontStyle: 'bold',
fontColor: '#FF0000'
}
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Response Time (ms)'
}
}]
},
plugins: {
datalabels: {
color: 'white',
display: function (context) {
return context.dataset.data[context.dataIndex] > 15;
},
font: {
weight: 'bold'
},
formatter: Math.round
}
},
maintainAspectRatio: true,
responsive: true,
showInlineValues: true,
centeredInllineValues: true,
tooltipCaretSize: 0
}
});
}
This is what I see in console window:
Labels Array: 0-350,350-700,700-1000,1000-1500
Data Array: 5065,32,27,3
What I see as legend is one rectangle, same color as first bar, followed by list of labels.

It seems that charts.js labels only works when you split the datasets.
Leaving an example.
https://jsfiddle.net/code4mk/1j62ey38/
datasets: [ {
label: 'Result',
fill:false,
data: aDatasets1,
backgroundColor: '#E91E63',
},
{
label: 'Result2',
fill:false,
data: aDatasets2,
backgroundColor: '#E91E93',
}];

Related

How can I move text around on a pie chart in ChartJS?

Wondering how I can move the text more to the left and create a new line between the labels. As you can see the "label" and "percentage" are on top of each other.
I'm using ChartJS v2.8.0 and ChartJS Plugin Labels 1.1.0
Current Look:
Desired Look:
Current code:
var chart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['T-Shirts', 'Sweaters'],
datasets: [{
backgroundColor: [$('#chart-color-1').val(), $('#chart-color-2').val()],
data: [$('#attire_1_percent').val(), $('#attire_2_percent').val()],
borderWidth: 0
}]
},
options: {
maintainAspectRatio: false,
legend: {
display: false
},
plugins: {
labels: [{
render: "label",
fontColor: '#fff',
},
{
render: 'percentage',
fontColor: '#fff',
}
],
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
return data.labels[tooltipItem.index] + ": " + data.datasets[0].data[tooltipItem.index] + "%"
}
},
},
}
});

Display different chart when clicking on side buttons

I am new to front-end and I created something like this: https://codepen.io/mihaela-dobre/pen/RwWGbNp
I have 3 side buttons and if I click on them, I see the same chart displayed.
How can I write a JS function in order to display something else? For example, I want to display this chart when clicking on the second button:
var ctx_3 = document.getElementById('chartEight').getContext('2d');
var chartEight = new Chart(ctx_3, {
type: 'line',
data: {
labels: ['2020-03-10','2020-03-11','2020-03-12'],
datasets: [{
label: 'Trust Higher Than Eight Profit Per Day',
data: [100,800,600],
borderColor: [
'rgba(251,127,20,1)',
'rgba(251,127,20,1)',
'rgba(251,127,20,1)'
],
borderWidth: 3,
lineTension: 0
}]
},
options: {
scales: {
yAxes: [{
ticks: {
fontColor: "#CCC",
beginAtZero: true
},
gridLines: {
zeroLineColor: "#CCC"
}
}],
xAxes: [{
display:true,
ticks: {
fontColor: "#CCC",
}
}]
},
legend: {
labels: {
fontSize: 20
}
},
hover: {
mode: 'y-axis'
},
tooltips: {
titleFontSize: 14,
bodyFontSize: 14
}
}
});
Can anyone help me with how I can make this chart appear when I click on the second button, the one with K/D?
Just add a click-listener on the label representing the button and draw the new chart:
document.getElementById("1").addEventListener('click', () => {
// ... create the new chart ...
});
Full code here: https://jsfiddle.net/akmjxynq/

How do I create a legend for a bar chart?

How do I create legends like the following:
So far I have the following:
I can't figure out how to specify labels for the legend. They don't provide examples either.
https://www.chartjs.org/docs/latest/configuration/legend.html
So far I have the following code:
var topClickSourcesChart = new Chart('dashboard-click-source-chart', {
type: 'bar',
data: {
labels: ["Facebook","Google","NONE",],
datasets: [{
data: [10,5,3,],
backgroundColor: ['#4D90C3', '#866DB2', '#EA6F98', '#61BDF6', '#768BB7'],
}],
},
options: {
scales: {
xAxes: [{
display: false,
}]
},
legend: {
position: 'right',
labels: {
boxWidth: 10,
}
}
}
});
To show a legend you need to set the label property of a dataset, so the type of output you are expecting can be built by creating a chart from the code as shown below. Fiddle -> https://jsfiddle.net/6nkcx8sq/
var topClickSourcesChart = new Chart('dashboard-click-source-chart', {
type: 'bar',
data: {
labels: ["Number of users"],
datasets: [{
label: 'Facebook',
data: [10],
backgroundColor: '#4D90C3',
},
{
label: 'Instagram',
data: [15],
backgroundColor: '#866DB2',
},
{
label: 'Twitter',
data: [7],
backgroundColor: '#EA6F98',
}],
},
options: {
scales: {
xAxes: [{
display: false,
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
legend: {
position: 'right',
labels: {
boxWidth: 10,
}
}
}
});
I was able to get it with the following, but it was a pain in the ass for loops due to the backgroundColor having to be inside the dataset.
var topClickSourceChart = new Chart('dashboard-click-source-chart', {
type: 'bar',
data: {
labels: ["Facebook","Google","NONE",],
datasets: [
{label: "Facebook", data: [10]},{label: "Google", data: [5]},{label: "NONE", data: [3]},
]
},
options: {
scales: {
xAxes: [{
display: false,
}],
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
},
legend: {
position: 'right',
labels: {
boxWidth: 10,
}
}
}
});
if (topClickSourceChart.data.datasets.length > 0) topClickSourceChart.data.datasets[0].backgroundColor = '#4D90C3';
if (topClickSourceChart.data.datasets.length > 1) topClickSourceChart.data.datasets[1].backgroundColor = '#866DB2';
if (topClickSourceChart.data.datasets.length > 2) topClickSourceChart.data.datasets[2].backgroundColor = '#EA6F98';
if (topClickSourceChart.data.datasets.length > 3) topClickSourceChart.data.datasets[3].backgroundColor = '#61BDF6';
if (topClickSourceChart.data.datasets.length > 4) topClickSourceChart.data.datasets[4].backgroundColor = '#768BB7';
Here is the JSP/JSTL loop:
data: {
labels: [<c:forEach items="${clickSources}" var="cs">"${cs.key}",</c:forEach>],
datasets: [
<c:forEach items="${clickSources}" var="cs">{label: "${cs.key}", data: [${cs.value}]},</c:forEach>
]
},
I still could not find a way to make the top of the bars rounded.

Chart.js 2.7: How to remove bar with value is 0 on the grouped bars?

I'm trying to remove the bar with value is 0 on grouped bar chart bars, but even though I see this solution many places it doesn't work for me.
What I want to do
I created this codepen. It contains a ChartJS grouped bar chart:
Vue.component('bar-chart', {
extends: VueChartJs.Bar,
mounted () {
this.renderChart({
labels: [1500,1600,1700,1750,1800,1850,1900],
datasets: [{
data: [168,17,0,190,0,276,108],
label: "Europe",
backgroundColor: "#3cba9f",
fill: false
}, {
data: [0,202,0,161,0,38,0],
label: "Asian",
backgroundColor: "#n8c9b2",
fill: false
},{
data: [0,202,0,161,224,38,0],
label: "Latin America",
backgroundColor: "#e8c3b9",
fill: false
}, {
data: [260,43,80,82,0,26,82],
label: "North America",
backgroundColor: "#c45850",
fill: false
}]
},
{
responsive: true,
maintainAspectRatio: false,
scales: {
xAxes: [{
categoryPercentage: 0.8,
barPercentage: 0.9
}],
yAxes: [{
scaleLabel: {
display: true
},
ticks: {
beginAtZero: true // minimum value will be 0.
}
}]
}
})
}
})
var vm = new Vue({
el: '.app'
})
Any idea on how to achieve the wanted behaviour?

Chartjs last label not shown

[UPDATE] The question seems to be solved (see comments). I will update the answer as soon as i am sure about it
I am trying to achieve a weather chart using chartjs library.
The chart will always have the weather date of the first day of the month and in addition to that one value in between (makes 24 values).
I want all "first day of the month" labels to be shown (with the corresponding gridline), the other data point in between should not be shown (or at least with no gridline).
The Problem now, somehow the last (12th) label is not gonna be shown and I have no idea why. The result looks like that:
My javascript code is that
var ctx = document.getElementById('canvas').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [
"01","","02","","03","","04", "","05","","06","","07","","08","","09","","10","","11", "","12",""
],
datasets: [{
label: 'Temperature [°C]',
data: [
1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6
],
borderColor: "rgb(0, 182, 206)",
pointRadius: 1,
backgroundColor: "rgba(0, 182, 206,0.4)"
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
legend:{
display:false // Suppress interactive legend
},
scales: {
xAxes: [{
scaleLabel: {
display: false,
labelString: 'Month'
} ,
afterTickToLabelConversion: function(data){
var xLabels = data.ticks;
xLabels.forEach(function (labels, i) {
if (xLabels[i].length == 0){
xLabels[i] = '';
}
});
},
ticks: {
//maxRotation: 0,
//minRotation: 0,
autoSkip: true,
maxTicksLimit: 12
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Temperature [°C]'
},
ticks: {
beginAtZero: true
}
}]
}
}
});
Do you have some ideas?

Categories