How can I hide legend text if it's zero? - javascript

I'm trying to hide the legend title of an item, if it's value is zero. There are similar problems existing here, but nothing led to solving my problem.
Below is my source code:
<script>
var ctx = document.getElementById('beratungsfelderChart');
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['Group A', 'Group B', 'Group C', 'Group D', 'Group E'],
datasets: [{
label: '# of Votes',
data: [0, 3, 3, 5, 2],
backgroundColor: [
'#172b4dD9',
'#2dce89D9',
'#231F20D9',
'#192d35D9',
'#3B6058D9'
]
}]
},
options: {
legend: {
labels: {
//filter: function(item, chart, context) {
// return !item.text.includes('Test');
//}
filter: function(item, context) {
return !context.dataset.data[context.dataIndex] == 0;
}
}
},
axis: {
scales: {
yAxes: [{
display: false
}],
xAes: [{
ticks: {
display: false
}
}]
}
},
plugins: {
datalabels: {
display: function(context) {
return context.dataset.data[context.dataIndex] > 1;
}
}
}
}
});
</script>
As you can see I tried a few potential solutions, but until now, nothing worked out unfortunately.
1. options -> legend -> labels
2. options -> plugins -> datalabels
I hope that someone can help me somehow.
Best,
Nader

You should use legend.labels.filter as follows.
legend: {
labels: {
filter: (legendItem, data) => data.datasets[0].data[legendItem.index] != 0
}
}
new Chart(document.getElementById('beratungsfelderChart'), {
type: 'doughnut',
data: {
labels: ['Group A', 'Group B', 'Group C', 'Group D', 'Group E'],
datasets: [{
label: '# of Votes',
data: [0, 3, 3, 5, 2],
backgroundColor: [
'#172b4dD9',
'#2dce89D9',
'#231F20D9',
'#192d35D9',
'#3B6058D9'
]
}]
},
options: {
legend: {
labels: {
filter: (legendItem, data) => data.datasets[0].data[legendItem.index] != 0
}
},
axis: {
scales: {
yAxes: [{
display: false
}],
xAes: [{
ticks: {
display: false
}
}]
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<canvas id="beratungsfelderChart" height="90"></canvas>

You can also use generateLabels instead of filter. it's a newer method and you would be able to change value and style of each legends. For example I've removed zero values and added data to each label :
new Chart(document.getElementById('beratungsfelderChart'), {
type: 'doughnut',
data: {
labels: ['Group A', 'Group B', 'Group C', 'Group D', 'Group E'],
datasets: [{
label: '# of Votes',
data: [0, 3, 3, 5, 2],
backgroundColor: [
'#192d35',
'#36A2EB',
'#FFCE56',
'#FF6384',
'#3B6058'
]
}]
},
options: {
legend: {
labels: {
generateLabels: function (chart) {
var newLegends = [];
chart.data.labels.forEach(function (label, index) {
if (chart.data.datasets[0].data[index] == 0) //zero values
return;
var legend = {
text: label + ' ('+chart.data.datasets[0].data[index]+')',
fillStyle: chart.data.datasets[0].backgroundColor[index]
};
newLegends.push(legend)
});
return newLegends;
}
}
},
axis: {
scales: {
yAxes: [{
display: false
}],
xAes: [{
ticks: {
display: false
}
}]
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<canvas id="beratungsfelderChart" height="90"></canvas>

Related

Chart js grouped bar chart with individual label

I'm trying to implement a grouped bar chart with label for each bar chart. I don't want to have second label as a legend, basically i want 2 labels: one for group and one for element in dataset.
Something like:
Where do i need to put the second label(Male/Female), i put this label in datasets but it's not working.
Where do i need to put the second label(Male/Female), i put this label in datasets but it's not working.
You should declare and configure another x-axis. In the following example inspired by your data, I use options.scales.x.ticks.callback (see Labeling Axes | Chart.js) which allows me to inject new labels.
const ctx = document.getElementById('myChart');
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Category 1', 'Category 2', 'Category 3', 'Category 4'],
datasets: [{
label: 'Dataset 1',
data: [3, 4, 4, 2],
stack: 'Stack 0'
}, {
label: 'Dataset 2',
data: [5, 3, 4, 7],
stack: 'Stack 0'
}, {
label: 'Dataset 3',
data: [3, 0, 4, 4],
stack: 'Stack 1'
}, {
label: 'Dataset 4',
data: [2, 5, 6, 2],
stack: 'Stack 1'
}]
},
options: {
scales: {
x: {
stacked: true,
ticks: {
font: {
weight: 'bold'
},
callback: () => 'Label 1 | Label 2'
}
},
x2: {
border: {
display: false
},
grid: {
display: false
}
},
y: {
stacked: true,
beginAtZero: true
}
},
plugins: {
legend: {
display: false
}
}
}
});
.chart-container {
position: relative;
width: 600px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js#4.2.0"></script>
<div class="chart-container">
<canvas id="myChart"></canvas>
</div>

format y axis labels in bold

i am a little bit confused, because i dont find any solution to make some points at the y-axis bold.
I want to change the style of the 'sum labels' to bold.
var mc1 = new Chart(document.getElementById("mychart"), {
type: 'horizontalBar',
data: {
labels: ["sum(A+B)",
"A",
"B",
"sum(C+D)",
"C",
"D"
],
datasets: [{
backgroundColor: '#0066b3',
label: '# von 5',
data: [5, 3, 2, 7.5, 3, 4.5]
}]
},
options: {
scales: {
xAxes: [{
ticks: {
suggestedMin: 0,
suggestedMax: 5,
beginAtZero: true
}
}],
yAxes: [{
ticks: {
barThickness: 30,
beginAtZero: true
}
}]
},
legend: {
display: false
},
responsive: true,
text: 'Mychart'
}
});
mc1.options.scales.yAxes[0].ticks.minor.fontWight = 'bold';
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.min.js"></script>
<canvas id="mychart"></canvas>
JSFiddle demo.
This is by default not possible in V2, in the upcomming release of V3 of the lib you can achieve this with the scriptable fontStyle option like in this example:
var options = {
type: 'bar',
data: {
labels: ["sum(A+B)",
"A",
"B",
"sum(C+D)",
"C",
"D"
],
datasets: [{
backgroundColor: '#0066b3',
label: '# von 5',
data: [5, 3, 2, 7.5, 3, 4.5]
}]
},
options: {
indexAxis: 'y',
scales: {
y: {
ticks: {
font: {
style: (tick) => (tick?.tick?.label.includes('sum') ? 'bold' : 'normal')
}
}
}
}
}
}
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/3.0.0-beta.13/chart.js" integrity="sha512-JS/WtaFglOYbXbMt9s52TO0QEzWljfCG2dFTC6aW9bJdP40kC37uoV+EzI06/LgpfX65oTnS1jUXxscH2xlG1Q==" crossorigin="anonymous"></script>
</body>

Bar Chart different Bars in the xAxis

I'm testing some charts libs and now I'm using Chartjs and I want to create A bar chart and on this chart I want to make each bar has your on x position value and a legend to it.
Something like this: https://codepen.io/mmoskorz/pen/maPExb, but in this case the chart left space for the other bars.
var ctx = document.getElementById("mybarChart").getContext("2d");
var mybarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['1', '2', '3'],
datasets: [{
label: 'Candidate A Votes',
backgroundColor: "#000080",
data: [90,0,0]
}, {
label: 'Candidate B Votes2',
backgroundColor: "#d3d3d3",
data: [0,70,0]
}, {
label: 'Candidate C Votes3',
backgroundColor: "#add8e6",
data: [0,0,45]
}]
},
options: {
legend: {
display: true,
position: 'top',
labels: {
fontColor: "#000080",
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
Only one X position doesn't satisfy my problem: https://codepen.io/mmoskorz/pen/aPNmNx
var ctx = document.getElementById("mybarChart").getContext("2d");
var mybarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['1'],
datasets: [{
label: 'Candidate A Votes',
backgroundColor: "#000080",
data: [90]
}, {
label: 'Candidate B Votes2',
backgroundColor: "#d3d3d3",
data: [70]
}, {
label: 'Candidate C Votes3',
backgroundColor: "#add8e6",
data: [45]
}]
},
options: {
legend: {
display: true,
position: 'top',
labels: {
fontColor: "#000080",
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
I tried to put values to x and y, but not work as well: https://codepen.io/mmoskorz/pen/OrNRXp
var ctx = document.getElementById("mybarChart").getContext("2d");
var mybarChart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
label: 'Candidate A Votes',
backgroundColor: "#000080",
data: [{x:90, y:1}]
}, {
label: 'Candidate B Votes2',
backgroundColor: "#d3d3d3",
data: [{x:70, y:2}]
}, {
label: 'Candidate C Votes3',
backgroundColor: "#add8e6",
data: [{x:45, y:3}]
}]
},
options: {
legend: {
display: true,
position: 'top',
labels: {
fontColor: "#000080",
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});

Where do I put the title (chart.js)?

I have made two charts in chart.js for a school project, one bar and one line and would like to put a title on each chart but it doesn't work, the bars only disappear. Where do i put the title in the code? I would like the titles to be above the two charts.
Here's a jsfiddle of the code to show more details: https://jsfiddle.net/b4d5y01z/1/
let lineConfig = {
type: 'line',
data: {
labels: ["2012", "2013", "2014", "2015", "2016", "2017"],
datasets: [{
label: 'Miljoner ton',
data: [56.38, 59.3, 61.81, 58.83, 52.32, 66.86],
backgroundColor:"rgba(0,255,0,0.4)",
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
},
barConfig = {
type: 'bar',
data: {
labels: ['Palmolja', "Sojaolja", 'Solrosolja', 'Rapsolja', 'Jordnöt','Annat'],
datasets: [{
label: "Miljoner ton",
data: [32, 22.4, 8, 13.1, 2.2, 19.7],
backgroundColor: "rgba(0,255,0,0.4)",
borderColor: "green", // The main line color
borderCapStyle: 'square',
pointBorderColor: "white",
pointBackgroundColor: "green",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "yellow",
pointHoverBorderColor: "green",
pointHoverBorderWidth: 2,
pointRadius: 4,
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
},
activeType = 'bar', // we'll start with a bar chart.
myChart;
function init(config) {
// create a new chart with the supplied config.
myChart = new Chart(document.getElementById('chart'), config);
}
Replace options with following
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
},
title: {
display: true,
text: 'Custom Chart Title'
}
},
Demo https://jsfiddle.net/wkt0bfxp/
Try This:
let lineConfig = {
type: 'line',
data: {
labels: ['q', 'w', 'e', 'r', 't', 'y'],
datasets: [{
data: [6, 5, 4, 3, 2, 1]
}]
},
options: {
title:{
display: true,
text: "My Second Chart"
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
},
barConfig = {
type: 'bar',
data: {
labels: ['a', 's', 'd', 'f', 'g', 'h'],
datasets: [{
data: [10, 20, 30, 40, 50, 60]
}]
},
options: {
title:{
display: true,
text: "My First Chart"
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
},
Try using charty.live,which gives the developers, the leverage to create charts without single line of code.

set different colors for each column in highcharts

I need to set different colors for each column in Highcharts graph dynamically. My Highcharts graph is:
options = {
chart: {
renderTo: 'chart',
type: 'column',
width: 450
},
title: {
text: 'A glance overview at your contest’s status'
},
xAxis: {
categories: ['Approved Photos', 'Pending Approval Photos',
'Votes', 'Entrants'],
labels: {
//rotation: -45,
style: {
font: 'normal 9px Verdana, sans-serif, arial'
}
}
},
yAxis: {
allowDecimals: false,
min: 0,
title: {
text: 'Amount'
}
},
legend: {
enabled: false
},
series: []
};
series = {
name: "Amount",
data: [],
dataLabels: {
enabled: true,
color: '#000000',
align: 'right',
x: -10,
y: 20,
formatter: function () {
return this.y;
},
style: {
font: 'normal 13px Verdana, sans-serif'
}
}
};
The data is set this way:
for (var i in Data) {
if (parseInt(Data[i]) != 0) {
series.data.push(parseInt(Data[i]));
} else {
series.data.push(null);
}
}
options.series.push(series);
chart = new Highcharts.Chart(options);
How can I dynamically set different colors for each data point in this loop?
Here is another solution with the latest version of Highcharts (currently 3.0).
Set the colorByPoint option to true and define the color sequence that you want.
options = {
chart: {...},
plotOptions: {
column: {
colorByPoint: true
}
},
colors: [
'#ff0000',
'#00ff00',
'#0000ff'
]
}
Here is an example based upon Highcharts Column with rotated labels demo
When you add the value to the series.data you can also set the color using the point options e.g
series.data.push({ y: parseInt(Data[i]), color: '#FF0000' });
For more details about the point options see https://api.highcharts.com/class-reference/Highcharts.Point#color
Try either of these approaches:
Approach 1:
Highcharts.setOptions({ colors: ['#3B97B2', '#67BC42', '#FF56DE', '#E6D605', '#BC36FE'] });
Approach 2:
var colors = ['#3B97B2', '#67BC42', '#FF56DE', '#E6D605', '#BC36FE', '#000'];
$('#bar_chart').highcharts({
chart: {
type: 'column'
},
title: {
text: ''
},
subtitle: {
text: ''
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
text: ''
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: false
}
}
},
series: [{
name: '',
colorByPoint: true,
data: [{
name: 'Blue',
y: 5.78,
color: colors[0]
}, {
name: 'Green',
y: 5.19,
color: colors[1]
}, {
name: 'Pink',
y: 32.11,
color: colors[2]
}, {
name: 'Yellow',
y: 10.04,
color: colors[3]
}, {
name: 'Purple',
y: 19.33,
color: colors[4]
}]
}]
});
i had colors from API response and 2 series. second series with dynamic colors.
following is sample to set dynamic colors while series mapping.
const response = [{
'id': 1,
'name': 'Mango',
'color': '#83d8b6',
'stock': 12.0,
'demand': 28,
},
{
id ': 2,
'name': 'Banana',
'color': '#d7e900',
'stock': 12.0,
'demand': 28,
}
];
let chartData: {
categories: [],
series: []
};
chartData.categories = response.map(x => x.name);
chartData.series.push({
name: 'Series 1',
type: 'column',
data: response.map(x => x.demand)
});
chartData.series.push({
name: 'Series 2',
type: 'column',
data: response.map(x => ({
y: x.stock,
color: x.color // set color here dynamically
}))
});
console.log('chartData: ', chartData);
you could also read more about Highcharts series Point and Marker

Categories

Resources