chart.js - problem with label on the right hand - javascript

I use chart.js and I would like to display labels at the right of each bar but I got a problem with the first label.
I use the plugin chartjs-plugin-datalabels it work but the first label is hidden.
Do you know how to fix this?
https://jsfiddle.net/rq78pg4j/1/
var ctx4 = $('#chart_choice');
var chart_market = new Chart(ctx4, {
type: 'horizontalBar',
data: {
labels: ['Legend 1', 'Legend 2'],
datasets: [{
data: [12, 10],
label: '# of Votes',
backgroundColor: [
'rgba(243,212,205,1)',
'rgba(243,212,205,1)'
],
borderColor: [
'rgba(223,142,123,1)',
'rgba(223,142,123,1)'
],
borderWidth: 1
}]
},
options: {
plugins: {
datalabels: {
align: 'end',
anchor: 'end',
color: '#0B4892',
font: function(context) {
var w = context.chart.width;
return {
size: w < 512 ? 12 : 14,
weight: 'bold',
};
},
formatter: function(value, context) {
return context.chart.data.labels[context.dataIndex];
}
}
}
}
});

The problem is that Chart.js is not aware of what chartjs-plugin-datalabels is doing. Therefore, it doesn't reserve enough space at the right of the chart, allowing the labels of the largest bars to appear on the canvas.
This can be fixed by defining extra padding at the right of the chart as follows.
options: {
layout: {
padding: {
right: 100
}
},
...
For further details, please consult the page Layout Configuration from the Chart.js documentation.

Related

Chart JS : Display the percentage of labels without getContext('2d')

I'm using the library chartJs to display the data that i get from my MySQL database.
In the fucntion below, AddValuesToNavigatorChart takes the browsers data and the percentage data and displays them on the pie chart.
What i need to know, is how to add '%' in my labels ?
I found few answer with getContent('2d').. using the old way, but it's not working.
This is the function :
function AddValuesToNavigatorChart(browsers, percentage) {
checkNavigatorChart()
const data = {
labels: browsers,
datasets: [{
data: percentage,
backgroundColor: [
'rgb(192,192,192)',
'rgb(255,0,0)',
'rgb(0,0,0)',
'rgb(105,105,105)'
],
hoverOffset: 4
}]
};
const config = {
tooltips: {
enabled: false
},
type: 'pie',
data: data,
plugins: [ChartDataLabels],
options: {
showTooltips: false,
plugins: {
datalabels: {
color: 'rgb(255,255,255)',
borderWidth: '2',
align: 'top'
},
legend: {
position: 'bottom',
align: 'center',
labels: {
boxWidth: 12,
padding: 15,
usePointStyle: true,
pointStyle: 'circle'
}
},
title: {
text: 'Navigator Chart',
display: true,
color: 'rgb(0,0,0)',
position: 'top'
}
}
}
};
const NavigatorChart = new Chart(
document.getElementById('NavigatorChart'),
config
);
}
Please provide the version of chartjs that you are using.
Did you mean you want to show the % in the label of the tooltip?
For version v3.8.0, here is a working code I have just made, Link
As in option, you can edit the label of tooltip as you want:
options: {
plugins: {
tooltip: {
callbacks: {
label: (tooltipItem) => {
//tooltipItem is for the slice of the pie you are hovering now
return ' ' + tooltipItem.parsed + '%';
},
}
}
}
}

Styling problems with Chart.Js

How can I add these styles to my graph? I'm having trouble finding it in the documentation for it, and the other forums aren't very helpful. I am using Flask for the backend, so that's why the data values look like that.
Labels on top of bars
Change font size on both axis
Set y scale as a fixed value (0,8)
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var options = {
scales: {
yAxes: [{
ticks: {
fontSize: 40
}
}]
}
}
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Lithium Battery', 'Other Mfg', 'Delivery', 'Tailpipe', 'Fuel Cycle', 'Disposal', 'Total'],
datasets: [{
label: 'ICEV CAR (MTCO2e/Year)',
labels: [
"{{data['battery_icev_car']}}",
"{{data['other_mfg_icev_car']}}",
"{{data['delivery_icev_car']}}",
"{{data['tailpipe_icev_car']}}",
"{{data['fuel_cycle_icev_car']}}",
"{{data['disposal_icev_car']}}",
"{{data['total_icev_car']}}"
],
data: [ /* errors are normal, fixes when server ru
[0, {{data['y1_icev']}}],
[{{data['y1_icev']}}, {{data['y2_icev']}}],
[{{data['y2_icev']}}, {{data['y3_icev']}}],
[{{data['y3_icev']}}, {{data['y4_icev']}}],
[{{data['y4_icev']}}, {{data['y5_icev']}}],
[{{data['y5_icev']}}, {{data['y6_icev']}}],
[0, {{data['y6_icev']}}]
],
backgroundColor: [
'rgba(0,0,0,0.9)'
],
borderColor: [
'rgba(0,0,0,1)'
],
borderWidth: 1,
borderSkipped: false
}]
},
options: {
responsive: true,
plugins: {
legend: {
labels: {
// This doesn't work on axis
font: {
size: 20
}
}
}
},
y: {
beginAtZero: true
}
}
});
</script> </script>
Since your config is not working I assume you are using V3, in which case the solution is as followed:
For point one you need to use an external plugin, you can write your own or use the datalabels plugin
For your second problem you need to style it as a font object as told in the documentation like so:
options: {
scales: {
y:{
ticks:{
font:{
size: 50
}
}
}
}
}
For your last part you can set the stepSize to 0.8

Chart.js - change which data the legend uses for the coloured box

I have a bar chart that always shows 4 bars. The bars are coloured dynamically. It looks like the coloured box takes its colour from the first data. I would like to use the colour from the 4th (last) data value. Maybe the options:plugins:legend:label:sort function helps but I don't understand what it does.
options
const options = {
scales: {
x: {
grid: {
display: false,
color: 'rgba(0,0,0)'
}
},
y: {
display: false,
min: 0,
max: 4
},
},
plugins: {
legend: {
position: 'bottom'
}
}
}
So I don't know if I can change the data that the box color comes from, or if there is a config option somewhere where I can change it manually.
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: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow'],
datasets: [{
label: 'My Dataset',
data: [300, 50, 100],
backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56']
}]
},
options: {
responsive: false,
plugins: {
legend: {
labels: {
generateLabels: chart => {
let ds = chart.data.datasets[0];
let color = ds.backgroundColor[ds.backgroundColor.length - 1];
return [{
datasetIndex: 0,
text: ds.label,
fillStyle: color,
strokeStyle: color
}];
}
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="myChart" height="180"></canvas>
Following up with #uminder's answer, if you want to keep the hide/show chart and the line-through style after clicking on the legend, you can add the following line:
options: {
responsive: false,
plugins: {
legend: {
labels: {
generateLabels: chart => {
let ds = chart.data.datasets[0];
let color = ds.backgroundColor[ds.backgroundColor.length - 1];
return [{
datasetIndex: 0,
text: ds.label,
fillStyle: color,
strokeStyle: color,
+ hidden: !chart.isDatasetVisible(0)
}];
}
}
}
}
}

Chart.js stacked line chart with differently styled sections

My React app uses react-chartjs-2 (which in turn uses the latest Chart.js 2.7.2). I'm trying to create stacked line charts with a differently styled section between the second-to-last and last x-axis labels, as shown in this example:
How can this be accomplished?
I solved it myself by separating the stacked line data into 2 datasets, to plot as separate stacked plots on the same figure/axes (by including the 2 separate datasets in a single chart's data object).
#Izzi (from comment) here is example:
Link with examle: https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html
Paste this config into editor on the website linked above:
data
const data = {
labels: generateLabels(),
datasets: [
{
label: 'Data A',
data: [40.96,89.06,65.46,45.46,89.55,54.52,71.24,89.1],
borderColor: Utils.CHART_COLORS.red,
backgroundColor: Utils.CHART_COLORS.red,
// look at this setting
fill: 'origin'
},
{
label: 'Data B',
data: [20.96,65.06,15.46,34.46,53.55,24.52,31.24,59.1],
borderColor: Utils.CHART_COLORS.blue,
backgroundColor: Utils.CHART_COLORS.blue,
fill: 'origin'
},
{
label: 'Data C',
data: [20.96,65.06,15.46,34.46,53.55,24.52,31.24,59.1],
borderColor: Utils.CHART_COLORS.green,
backgroundColor: Utils.CHART_COLORS.green,
fill: 'origin'
}
]
};
config
const config = {
type: 'line',
data: data,
options: {
scales: {
y: {
// look at this setting
stacked: true,
}
},
plugins: {
filler: {
propagate: false,
},
title: {
display: true,
text: (ctx) => 'Fill: ' + ctx.chart.data.datasets[0].fill
}
},
interaction: {
intersect: false,
}
},
};

How to show bar labels in legend in Chart.js 2.1.6?

I'm creating charts using Chart.js and I want to show the labels for the bars in the legend, not the title of the dataset (there is only one), please see the below image as an example:
My current legend just looks like this:
I have looked through the docs but to no avail, I found them very confusing actually.
Here is my current code:
var chart_0 = new Chart($('#cp_chart_0'), {
type: 'bar'
, data: {
labels: ['Blue','Green','Yellow','Red','Purple','Orange']
, datasets: [{
label: 'Dataset 1'
, borderWidth: 0
, backgroundColor: ['#2C79C5','#7FA830','#7B57C3','#ED4D40','#EC802F','#1DC6D3']
, data: ['12','2','5','0','9','1']
}]
}
});
Thanks!
In one of the most recent releases of Chart.js 2.1.x, they added back this functionality. So go get the latest release first. Then insert the code below.
It is located under the options and legend. Here is how you use it:
options: {
legend: {
position: 'right'
}
}
Easiest way is to provide your data with multiple sets :
data: {
labels: ['total votes']
, datasets: [{
label: 'Blue'
, backgroundColor: ['#2C79C5']
, data: ['12']
},{
label: 'Green'
, backgroundColor: ['#7FA830']
, data: ['2']
},
...
]
}
But you can generate a custom labels using generateLabels - http://www.chartjs.org/docs/#chart-configuration-legend-configuration
Or even customise the whole legend, including formatting, with legendCallback - http://www.chartjs.org/docs/#chart-configuration-common-chart-configuration
This solution uses Chart.js version 3. You can pre-process your data using the Plugin Core API. The API offers different hooks that may be used for executing custom code.
I use the beforeInit hook to create individual datasets for each defined label/value pair. Note that the data of these new datasets are defined in point format (for instance [{ x: 1, y: 12 }]):
beforeInit: chart => {
let dataset = chart.config.data.datasets[0];
chart.config.data.datasets = chart.config.data.labels.map((l, i) => ({
label: l,
data: [{ x: i + 1, y: dataset.data[i] }],
backgroundColor: dataset.backgroundColor[i],
categoryPercentage: 1
}));
chart.config.data.labels = undefined;
}
Further you need to define a second x-axis that will contain the labels.
x1: {
offset: true,
gridLines: {
display: false
}
}
The labels on x1 need to be collected and defined programmatically each time the hidden state of a dataset changes. This can be done in the beforeLayout hook.
beforeLayout: chart => chart.options.scales.x1.labels = chart.config.data.datasets.filter((ds, i) => !chart.getDatasetMeta(i).hidden).map(ds => ds.label)
Please take a look at below runnable code and see how it works.
new Chart('chart', {
type: 'bar',
plugins: [{
beforeInit: chart => {
let dataset = chart.config.data.datasets[0];
chart.config.data.datasets = chart.config.data.labels.map((l, i) => ({
label: l,
data: [{ x: i + 1, y: dataset.data[i] }],
backgroundColor: dataset.backgroundColor[i],
categoryPercentage: 1
}));
chart.config.data.labels = undefined;
},
beforeLayout: chart => chart.options.scales.x1.labels = chart.config.data.datasets.filter((ds, i) => !chart.getDatasetMeta(i).hidden).map(ds => ds.label)
}],
data: {
labels: ['Blue', 'Green', 'Yellow', 'Red', 'Purple', 'Orange'],
datasets: [{
data: ['12', '2', '5', '0', '9', '1'],
backgroundColor: ['#2C79C5', '#7FA830', '#FFF200', '#ED4D40', '#800080', '#EC802F']
}]
},
options: {
interaction: {
intersect: true,
mode: 'nearest'
},
plugins: {
legend: {
position: 'right'
},
tooltip: {
callbacks: {
title: () => undefined
}
}
},
scales: {
y: {
beginAtZero: true
},
x: {
display: false
},
x1: {
offset: true,
gridLines: {
display: false
}
}
}
}
});
canvas {
max-width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.2.0/chart.min.js"></script>
<canvas id="chart" height="120"></canvas>

Categories

Resources