Anyone knows how can I truncate the legend's label using substr() in Chart.js Doughnut Chart using a callback maybe?
Greatly appreciated
You can use the generateLabels function as described here.
Please take a look at below runnable sample code and see how it works.
new Chart("myChart", {
type: 'doughnut',
data: {
labels: ["1. Red", "2. Blue", "3. Yellow"],
datasets: [{
data: [300, 50, 100],
backgroundColor: ["#FF6384", "#36A2EB", "#FFCE56"],
weight: 0.6
}]
},
options: {
plugins: {
legend: {
labels: {
generateLabels: chart => chart.data.labels.map((l, i) => ({
datasetIndex: 0,
index: i,
text: l.substr(3),
fillStyle: chart.data.datasets[0].backgroundColor[i],
strokeStyle: chart.data.datasets[0].backgroundColor[i],
hidden: false
}))
}
}
}
}
});
canvas {
max-height: 250px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="myChart"></canvas>
Related
I am looking to build the same as shown in the image, I checked chart.js documentation(https://www.chartjs.org/docs/3.0.2/) but didn't find anything like this. Is it possible to create a chart like this using chart.js?
Yes you can use the datalabels plugin to achieve what you want:
Example:
Chart.register(ChartDataLabels);
var options = {
type: 'bar',
data: {
labels: ["Category 1", "Category 2", "Category 3"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3],
animals: ['cat', 'dog', 'bear'],
borderWidth: 1,
backgroundColor: ['orange', 'blue', 'gray']
},
{
label: '# of Points',
data: [7, 11, 5],
animals: ['monkey', 'bird', 'fish'],
borderWidth: 1,
backgroundColor: ['yellow', 'cyan', 'purple']
}
]
},
options: {
plugins: {
title: {
display: true,
text: 'title'
},
datalabels: {
anchor: 'end', // remove this line to get label in middle of the bar
align: 'end',
formatter: (val, x) => (x.dataset.animals[x.dataIndex]),
labels: {
value: {
color: 'purple'
}
}
}
}
}
}
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.2/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2.0.0-rc"></script>
</body>
you can use Plotly.js for grouped chart please check below code
Reference URL : https://plotly.com/javascript/bar-charts/
var trace1 = {
x: ['giraffes', 'orangutans', 'monkeys'],
y: [20, 14, 23],
name: 'SF Zoo',
type: 'bar'
};
var trace2 = {
x: ['giraffes', 'orangutans', 'monkeys'],
y: [12, 18, 29],
name: 'LA Zoo',
type: 'bar'
};
var data = [trace1, trace2];
var layout = {barmode: 'group'};
Plotly.newPlot('myDiv', data, layout);
<head>
<!-- Load plotly.js into the DOM -->
<script src='https://cdn.plot.ly/plotly-1.58.4.min.js'></script>
</head>
<body>
<div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
</body>
I have tried to make a pie chart using react-chartjs 2, It is working fine in desktop view but in mobile view the legend is not responsive it is taking much space and due to this the size of pie chart become very small.
my code:
function Chart(props: any) {
const option = {
tooltips: {enter image description here
callbacks: {
label: function (tooltipItem: any, data: any) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var meta = dataset._meta[Object.keys(dataset._meta)[0]];
var total = meta.total;
var currentValue = dataset.data[tooltipItem.index];
var percentage = parseFloat(
((currentValue / total) * 100).toFixed(1)
);
return currentValue + " (" + percentage + "%)";
},
title: function (tooltipItem: any, data: any) {
return data.labels[tooltipItem[0].index];
},
},
},
legend: {
display: true,
labels: {
fontSize: 12,
},
position: "right",
},
};
return (
<div className="chart">
<Pie data={props.ChartData} options={option} />
</div>
);
You can set your fontSize object as a ternery operator that checks the widts (or something else) to see if you are on a mobile device and give back the right fontSize according to it
If you want to update it real time because screen sizes change you can do that by mutating the chart options itself in a resizeEvent listner
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: {
legend: {
labels: {
fontSize: window.innerWidth > 350 ? 20 : 10
}
},
scales: {
yAxes: [{
ticks: {
reverse: false
}
}]
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);
window.addEventListener('resize', () => {
if (window.innerWidth < 350) {
chart.options.legend.labels.fontSize = 10;
} else {
chart.options.legend.labels.fontSize = 20
}
});
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js" integrity="sha512-hZf9Qhp3rlDJBvAKvmiG+goaaKRZA6LKUO35oK6EsM0/kjPK32Yw7URqrq3Q+Nvbbt8Usss+IekL7CRn83dYmw==" crossorigin="anonymous"></script>
</body>
Here is the way to have a responsive legend font size (also explained here)
options: {
plugins: {
legend: {
labels: {
// This more specific font property overrides the global property
font: {
size: 14
}
}
}
}
}
I'm using ChartJS with the plug-in ChartJS DataLabels to show text values right next to the points (who would have thought that a plugin is necessary for this basic task, but I digress).
My issue I need to vary the color of my text labels along with the individual dataset. But so far I haven't found a solution. I'm adding new datasets dynamically, they're not statically pre-loaded. The color should match the color of the dataset.
Suppose I have
var colorpalette = ["red", "blue", "green", "magenta", "yellow", "brown", "purple", "orange", "black", "gray"];
var currseriesnum = 0;
var chart = null;
function setUpChart() {
var ctx = document.getElementById('chartArea').getContext('2d');
chart = new Chart(ctx, {
type: 'line',
data: {
labels: monthnames,
datasets: [] // Initially blank - series added dynamically with chart.update()
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
plugins: { // ChartsJS DataLabels initialized here
datalabels: {
anchor: 'end',
align: 'bottom',
formatter: Math.round,
font: {
weight: 'bold',
size: 16
},
color: colorpalette[currseriesnum] // Pick color dynamically
}
}
}
});
}
Doesn't work. Also tried a function, color: function(context), but unsure how to retrieve the current index of the dataset I'm getting here.
I'm adding series to the chart dynamically (initially empty) as below, and incrementing the global var currseriesnum.
chart.data.datasets.push({
label: keyValueSelection.label,
fill: false,
data: keyValueSelection.value,
borderColor: colorpalette[currseriesnum],
borderWidth: 2
});
chart.update();
currseriesnum++;
They gave me the answer on the ChartJS DataLabels forum:
plugins: {
datalabels: {
color: function(ctx) {
// use the same color as the border
return ctx.dataset.borderColor
}
}
}
I have the following code to create a graph using Chart.js v2.1.3:
var ctx = $('#gold_chart');
var goldChart = new Chart(ctx, {
type: 'line',
data: {
labels: dates,
datasets: [{
label: 'I want to remove this Label',
data: prices,
pointRadius: 0,
borderWidth: 1
}]
}
});
The code looks simple, but I cannot remove the label from the graph. I tried a lot of solutions I found online, but most of them use Chart.js v1.x.
How can I remove the dataset labels?
Just set the label and tooltip options like so
...
options: {
legend: {
display: false
},
tooltips: {
callbacks: {
label: function(tooltipItem) {
return tooltipItem.yLabel;
}
}
}
}
Fiddle - http://jsfiddle.net/g19220r6/
As of 2021, the namespace has changed from options.legend to options.plugins.legend. This simple code worked for me -
options: {
plugins: {
legend: {
display: false
}
}
}
Documentation reference
add:
Chart.defaults.global.legend.display = false;
in the starting of your script code;
New Solution ChartJS v3.1.1
The above solution is correct for previous versions of chart js prior to v3.1 for v3.1.1 use the following
...
options: {
plugins:{
legend: {
display: false
}
}
}
For those who want to remove the actual axis labels and not just the legend in 2021 (Chart.js v.3.5.1). Note: this also removes the axes.
const chartWrap = document.querySelector('.chart-wrap')
const canvas = document.createElement('canvas')
chartWrap.appendChild(canvas)
const ctx = canvas.getContext('2d')
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Your', 'axis', 'labels'],
datasets: [
{
label: 'Your legend label',
data: [1, 3, 2],
backgroundColor: '#54ACEF'
}
]
},
options: {
maintainAspectRatio: false,
plugins: {
legend: false // Hide legend
},
scales: {
y: {
display: false // Hide Y axis labels
},
x: {
display: false // Hide X axis labels
}
}
}
})
<div class="chart-wrap" style="width: 200px; height: 100px;"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js" integrity="sha512-Wt1bJGtlnMtGP0dqNFH1xlkLBNpEodaiQ8ZN5JLA5wpc1sUlk/O5uuOMNgvzddzkpvZ9GLyYNa8w2s7rqiTk5Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
You can also put the tooltip onto one line by removing the "title":
this.chart = new Chart(ctx, {
type: this.props.horizontal ? 'horizontalBar' : 'bar',
options: {
legend: {
display: false,
},
tooltips: {
callbacks: {
label: tooltipItem => `${tooltipItem.yLabel}: ${tooltipItem.xLabel}`,
title: () => null,
}
},
},
});
It's just as simple as adding this:
legend: {
display: false,
}
Or if you want you could use this other option which should also work:
Chart.defaults.global.legend.display = false;``
new Chart('idName', {
type: 'typeChar',
data: data,
options: {
legend: {
display: false
}
}
});
Replace options with this snippet, will fix for Vanilla JavaScript Developers
options: {
title: {
text: 'Hello',
display: true
},
scales: {
xAxes: [{
ticks: {
display: false
}
}]
},
legend: {
display: false
}
}
I'm trying to use Google charts to display the results of a survey. All seems fine, apart from the title of the vAxis is being cut off slightly and I can't work out how to move it closer to the axis.
This is the code:
google.load("visualization", "1.0", {packages:["bar"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Question title goes here', 'Percentage Score'],
['Always', 40],
['Usually', 30],
['Rarely', 10],
['Never', 20]
]);
var options = {
chart: {
title: 'Section Title',
subtitle: 'Section subtitle',
},
legend: { position: "none" },
vAxis: {
title: 'Percentage',
viewWindowMode:'explicit',
viewWindow: {
max:100,
min:0
}
},
bars: 'vertical', // Required for Material Bar Charts.
width: 600,
height: 500
};
var chart = new google.charts.Bar(document.getElementById('barchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
};
I have a fiddle here:
https://jsfiddle.net/SBComms/pa4yLcb3/
With a Core Chart, you can adjust the size of the chartArea to allow room for the title.
However, this doesn't appear to work for a Material Chart.
Also, I would recommend loading with loader.js vs. the older library jsapi.
See following example...
google.charts.load('current', {
callback: drawChart,
packages: ['bar', 'corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Question title goes here', 'Percentage Score'],
['Always', 40],
['Usually', 30],
['Rarely', 10],
['Never', 20]
]);
var options = {
chart: {
title: 'Section Title',
subtitle: 'Section subtitle',
},
chartArea: {
backgroundColor: 'cyan',
height: 400,
left: 60,
top: 20,
width: 500
},
legend: {
position: "none"
},
vAxis: {
title: 'Percentage',
viewWindowMode:'explicit',
viewWindow: {
max:100,
min:0
}
},
bars: 'vertical',
width: 600,
height: 500
};
var chart = new google.charts.Bar(document.getElementById('barchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
var chart2 = new google.visualization.ColumnChart(document.getElementById('barchart_core'));
chart2.draw(data, options);
};
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div>========MATERIAL========</div>
<div id="barchart_material"></div>
<div>==========CORE==========</div>
<div id="barchart_core"></div>
I managed to find a real fiddle to the problem. I have updated the chart script so that the vAxis fontSize is 18:
google.load("visualization", "1.0", {packages:["bar"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['', 'Percentage'],
['Always', 40],
['Usually', 30],
['Rarely', 10],
['Never', 20]
]);
var options = {
chart: {
title: 'Company Performance'
},
legend: { position: "none" },
vAxis: {
title: 'Percentage',
titleTextStyle: {
fontSize: '18',
},
viewWindowMode:'explicit',
viewWindow: {
max:100,
min:0
}
},
bars: 'vertical', // Required for Material Bar Charts.
width: 400,
height: 400
};
var chart = new google.charts.Bar(document.getElementById('barchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
};
I have then added a CSS setting to force the font size back to normal:
#barchart_material g text {
font-size: 12px !important;
}
I have updated the fiddle here: https://jsfiddle.net/SBComms/pa4yLcb3/1/