hide label on doughnut chart of chartjs - javascript

Thanks for the help in advance.I am using doughnut graph of chartjs.In it the percentage value labels are coming on the graph.Is there any way i can hide it.
var category_doughnut_datas = [80,5,5,10];
var category_doughnut__data = {
labels: ["Safe Zone", "Level 1","Level 2","Level 3"],
};
var category_doughnut_options = {
cutoutPercentage: 60,
legend: {
display: false,
position: "top",
paddingBottom: 16,
align: "start",
labels: {
fontColor: "#555555",
fontSize: 20,
boxWidth: 0,
},
},
tooltips: {
displayColors: false,
},
responsive: true,
};
var dough_ctx = document.getElementById("overallStatus").getContext("2d");
if (dough_ctx) {
var myDoughnutChart = new Chart(dough_ctx, {
type: "doughnut",
data: category_doughnut__data,
options: category_doughnut_options,
});
}

Since you dont specify any options to draw it on the chart in your options and its not default chart.js behaviour I expect you defined it as defaults somewhere, in which case you can in your options object in the plugins section specify datalabels: false to stop it from rendering:
Chart.register(ChartDataLabels);
Chart.defaults.plugins.datalabels.color = '#fff';
Chart.defaults.plugins.datalabels.formatter = (value, ctx) => {
let sum = 0;
let dataArr = ctx.chart.data.datasets[0].data;
dataArr.map(data => {
sum += data;
});
let percentage = (value * 100 / sum).toFixed(2) + "%";
return percentage;
};
const options = {
type: 'doughnut',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
}]
},
options: {
plugins: {
datalabels: false // Removing this line shows the datalabels again
}
}
}
const 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.5.1/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.js"></script>
</body>

options.plugins.datalabels: false should be mentioned.
Without it, the value is set to be true by default.

Related

Chart.js v3 - beginAtZero does nothing to my chart

I read many threads on the beginAtZero parameter in Chart.js, but none of the solutions I found actually work for me.
I have a simple line chart with dates on my x axe and integers in my y axe. I can't manage to make my y axe start with 0.
let atchoum = document.querySelector("#atchoum")
let statchoum = new Chart(atchoum, {
type: "line",
data: {
labels: {{ atchoumDate|raw }},
datasets: [{
label: "Nombre d'éternuements au support",
data: {{ atchoumNb|raw }},
borderColor: "blue",
tension: 0.3,
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
},
animations: {
y: {
easing: 'easeInOutElastic',
from: (ctx) => {
if (ctx.type === 'data') {
if (ctx.mode === 'default' && !ctx.dropped) {
ctx.dropped = true;
return 0;
}
}
}
}
},
}
}]
}
})
You are defining your options in the dataset itself.
The options object is supposed to be on the same level as the type and data fields since the options are for the entire chart and not for a single dataset.
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 7, 9, 20, 8]
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
}
const 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.5.1/chart.js"></script>
</body>

Chart.JS tooltip callbacks label and title (v3.5)

(Please note: There are lots of answers for v2, this is for v3)
I'm trying to setup tooltips label and title for a doughnut chart.
Code:
//Create the donut chart
donut = new Chart('questions_positivity_donut', {
type: 'doughnut',
data: {
labels: ["Positive", "Other"],
datasets: [{
label: 'Sentiment',
data: [user_context.state.avg_joy, (1-user_context.state.avg_joy)],
backgroundColor: ['#a9a9a9','#f2f2f2']
}]
},
options: {
cutout: "70%",
plugins: {
legend: {
display: false
},
maintainAspectRatio: false,
responsive: true,
tooltip: {
callbacks: {
label: function(context) {
let label = new Intl.NumberFormat('en-US', {style: 'percent', minimumFractionDigits: 0, maximumFractionDigits: 0}).format(context.formattedValue);
return label;
},
title: function(context) {
let title = context.parsed.x;
return title;
}
},
displayColors: false
}
}
}
});
The label now works, and displays the value of the data, but the title is returning blank, instead of returning the label of the data ("Positive" or "Other").
How can I return the correct title in the tooltip.callback?
Example: "Positive 35%" and "Other 65%"
If you log the context you could see its an array containing objects, with the default interaction mode you are using it only contains a single item so you can select that one and then access the label attribute on it like so:
var options = {
type: 'doughnut',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
}]
},
options: {
plugins: {
tooltip: {
callbacks: {
label: function(context) {
let label = new Intl.NumberFormat('en-US', {
style: 'percent',
minimumFractionDigits: 0,
maximumFractionDigits: 0
}).format(context.formattedValue);
return label;
},
title: function(context) {
let title = context[0].label;
return title;
}
},
}
}
}
}
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.5.1/chart.js"></script>
</body>

How can I move chartJs legend left side and change the width and Hight of the chart?

.html
<p-chart type="bar"></p-chart>
.TS
I have added the config part
config: [{
legend: {display: true, position: 'right'},
responsive: false,
},
I want to remove space that i show in red arrow. I want to get little bit left side chart legends
and want to change the width and hight of the chart
2 things, the config options for chart take an object and not an array, also the legend config has been moved to the plugins section so you will get this:
config: {
responsive: true,
plugins: {
legend: {
position: 'right'
}
}
}
Plain js example:
var options = {
type: 'pie',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [
{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1,
backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
}
]
},
options: {
plugins: {
legend: {
position: 'right'
}
}
}
}
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.3.0/chart.js"></script>
</body>

Chart.js remove label from legend for if dataset values

I have a chart with multiple datasets. I want the label of a dataset from the legend to not be visible if all the values in a dataset are null. I've found some solutions but they were only working if data was declared in the initial configuration. In my case it is dynamically updated.
Here is the code:
self.initGraph = function () {
ctxWell = document.getElementById("wellChart").getContext('2d');
if (wellChart != undefined)
wellChart.destroy();
wellChart = new Chart(ctxWell, {
type: 'line',
data: {
labels: [],
datasets: [
{
backgroundColor: reportColor.Green,
borderColor: reportColor.Green,
label: 'Motor Frequency Hz',
yAxisID: 'y-axis-2',
data: [],
borderWidth: 1,
pointRadius: 0,
fill: false
},
{
backgroundColor: reportColor.Turquoise,
borderColor: reportColor.Turquoise,
label: 'Pump Discharge Pressure ' + helpers.getListSelectedValue(self.dischargePressureID(), self.pressureList()),
yAxisID: 'y-axis-1',
data: [],
borderWidth: 1,
pointRadius: 0,
fill: false
}
,
]
},
options: {
maintainAspectRatio: false,
animation: {
duration: 0
},
scales: {
yAxes: [
{
id: 'y-axis-1',
// stacked: true,
scaleLabel: {
display: true,
fontSize: 18,
labelString: helpers.getListSelectedValue(self.intakePressureID(), self.pressureList())
},
ticks: {
beginAtZero: true
}
},
{
id: 'y-axis-2',
position: 'right',
display: self.checkAxis(),
scaleLabel: {
display: self.checkAxis(),
fontSize: 18,
labelString: "Hz, " + helpers.getListSelectedValue(self.motorTemperatureID(), self.temperatureList())
},
ticks: {
beginAtZero: true
}
}
]
},
elements: {
line: {
tension: 0.000001
}
},
legend: {
display: true,
onClick: wellChartLegendClick,
}
},
}
});
wellChart.update();
};
self.updateWellDaily = function () {
var chart = wellChart;
chart.data.labels = [];
for (var j = 0; j < chart.data.datasets.length; j++) {
chart.data.datasets[j].data = [];
}
for (var i = 0; i < self.wellResults().length; i++) {
chart.data.labels.push(self.wellResults()[i].reportedTime);
chart.data.datasets[0].data.push(self.wellResults()[i].motorFrequency);
chart.data.datasets[1].data.push(self.wellResults()[i].pumpDischargePressure);
}
chart.update();
};
self.initGraph();
self.updateWellDaily();
The legend filter function can be used for this, if you tell it to hide labels where in the dataset all data is zeros it will update dynamicly, see example:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 0],
borderWidth: 1,
backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
},
{
label: '# of Counts',
data: [1, 2, 3,4,5,2],
borderWidth: 1,
backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
}
]
},
options: {
plugins: {
legend: {
labels: {
filter: (legendItem, chartData) => (!chartData.datasets[legendItem.datasetIndex].data.every(item => item === 0))
}
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);
document.getElementById("tt").addEventListener("click", () => {
chart.data.datasets[1].data = [0, 0, 0, 0, 0, 0];
chart.update()
});
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<button id="tt">
change data
</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.1.0/chart.js" integrity="sha512-LlFvdZpYhQdASf4aZfSpmyHD6+waYVfJRwfJrBgki7/Uh+TXMLFYcKMRim65+o3lFsfk20vrK9sJDute7BUAUw==" crossorigin="anonymous"></script>
</body>

Render labels only when the data is available for a particular label

I'm creating an stack bar chart using chart.js. I need to hide the labels which don't have data on the current chart. As an example I want to only show "Prediction Success" label as data related to other labels are not there for the current date range. How can we do that?
You can use the legend filter like this:
var options = {
type: 'bar',
data: {
labels: ["Red", "Yellow", "Blue", "Yellow", "Green", "Purple", "Orange", "Green"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 0, 5, 6],
borderWidth: 1,
backgroundColor: 'red'
},
{
label: '# of NonVotes',
data: [],
borderWidth: 1,
backgroundColor: 'blue'
}
]
},
options: {
plugins: {
legend: {
labels: {
filter: (legendItem, chartData) => (legendItem, chartData, chartData.datasets[legendItem.datasetIndex].data.length > 0)
}
}
}
}
}
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.1.0/chart.js" integrity="sha512-LlFvdZpYhQdASf4aZfSpmyHD6+waYVfJRwfJrBgki7/Uh+TXMLFYcKMRim65+o3lFsfk20vrK9sJDute7BUAUw==" crossorigin="anonymous"></script>
</body>

Categories

Resources