Chartjs: How to offset ticks on radarchart? - chart.js

I'm trying to mimic this Radarchart with ChartJs.
How to offset the ticks to the left like so?
what I have (below)
options: {
scale: {
ticks: {
min: 0,
max: 5,
stepSize: 1,
showLabelBackdrop: false,
beginAtZero: true,
},
gridLines: {
color: 'rgba(0, 0, 0, 0.3)'
},
angleLines: {
display: false
},
},
},
Additionally: is displaying the 0 possible?

You need to do two things.
To show the 0 tick add this to your options.scale object:
ticks: {
beginAtZero: true,
min: -0.001,
}
Note that if you set min at zero it will not work. This is how the radar tick engine works.
To add an offset to the label override the tick render callback inside the same object, like this:
ticks: {
callback: (value) => `${value} `,
}
Note the extra spaces at the end. This is the padding. See the sample below
var options = {
responsive: false,
maintainAspectRatio: true,
scale: {
ticks: {
beginAtZero: true,
callback: (value) => `${value} `,
min: -0.001,
max: 5
}
}
};
var dataLiteracy = {
labels: [
"1", "2", "3", "4", "5"
],
datasets: [{
label: "Literacy",
backgroundColor: "rgba(179,181,198,0.2)",
borderColor: "rgba(179,181,198,1)",
pointBackgroundColor: "rgba(179,181,198,1)",
pointBorderColor: "#fff",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(179,181,198,1)",
data: [
2, 3, 4, 1, 2
]
}]
};
var ctx = document.getElementById("canvas");
var myRadarChart = new Chart(ctx, {
type: 'radar',
data: dataLiteracy,
options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.1/Chart.min.js"></script>
<canvas id="canvas" height="400" width="400"></canvas>

Try this in the chart options:
ticks: {
callback: (value) => {
return '${value}';
},

Related

Display Datalabel for an specific point in Chart Js

I'm trying to build a chart.js Line and with scatter points and I would like to have the datalabel to show just on the scatter points, I've tried to do it with datalabels plugin from chart js but it shows the datalabel for all datasets including the line, How can I show just the specific scatter points? this is what the code looks like:
Chart.register(ChartDataLabels);
fetch('https://raw.githubusercontent.com/ConeDigital/assets/main/data.json')
.then(response => response.json())
.then(data => {
var ctx = document.getElementById('myChart2').getContext('2d'),
chart = new Chart(ctx, {
type: 'line',
data: getChartData(data),
options: {
legend: {
display: false
},
plugins: {
datalabels: { // This code is used to display data values
anchor: 'end',
align: 'top',
font: {
weight: 'bold',
size: 16
}
}
},
tooltips: {
mode: 'index',
intersect: false,
callbacks: {
label: function (tooltipItem, data) {
return data.datasets[tooltipItem.datasetIndex].label + ': ' + tooltipItem.yLabel+"%";
},
labelColor: function (tooltipItem, chart) {
let border = ''
let background = ''
let colors
if ( tooltipItem.datasetIndex === 1 ) {
colors = {
borderColor: '#fff',
backgroundColor: '#001F5B'
}
} else {
colors = {
borderColor: '#fff',
backgroundColor: '#eb8484'
}
}
return colors
}
}
},
responsive: true,
scales: {
xAxes: [{
stacked: false,
scaleLabel: {
display: false,
labelString: 'Datum'
},
ticks: {
display: false
},
gridLines: {
display: false,
drawBorder: false,
}
}],
yAxes: [{
stacked: false,
ticks: {
display: false
},
gridLines: {
display: false,
drawBorder: false
},
scaleLabel: {
display: false,
labelString: 'Procent'
}
}]
}
}
});
})
function getChartData(json) {
var labels = [];
var omx_dataset = {
label: 'OMXS30',
borderColor: '#eb8484',
fill: false,
pointRadius: 0,
borderWidth: 1,
data: []
};
var gadd_dataset = {
label: "GADD SMP SEK",
borderColor: '#001F5B',
fill: false,
pointRadius: 0,
borderWidth: 1,
data: []
};
var mark1_dataset = {
label: 'Start',
borderWidth: 2,
borderColor: '#FF0000',
fill: false,
type: 'scatter',
data: [{
x: '2011-03-29',
y: 0
}],
pointRadius: 12
};
var mark2_dataset = {
label: '2016',
borderWidth: 2,
borderColor: '#FF0000',
fill: false,
type: 'scatter',
data: [{
x: '2015-12-31',
y: 20
}],
pointRadius: 12
};
var mark3_dataset = {
label: '2020',
borderWidth: 2,
borderColor: '#FF0000',
fill: false,
type: 'scatter',
data: [{
x: '2020-01-07',
y: 59
}],
pointRadius: 12
};
var mark4_dataset = {
label: '2022',
borderWidth: 2,
borderColor: '#FF0000',
fill: false,
type: 'scatter',
data: [{
x: '2022-01-03',
y: 109
}],
pointRadius: 12
};
json.map((point,i) => {
labels.push(point.Date)
const gadd_num = (point['GADD SMP SEK']*100).toFixed(2)
const omx_num = (point['OMXS30']*100).toFixed(2)
gadd_dataset.data.push(gadd_num)
omx_dataset.data.push(omx_num)
//console.log(point.Date)
//result1_dataset.data.push(point.date)
})
return {
labels: labels,
datasets: [omx_dataset, gadd_dataset, mark1_dataset, mark2_dataset, mark3_dataset, mark4_dataset]
}
}
Right now it shows all the datalabels from all the datasets and it looks messed up,
Thanks in advance
You could add the datalabels config to the line datasets, disabling the plugin, as the following:
var omx_dataset = {
label: 'OMXS30',
borderColor: '#eb8484',
fill: false,
pointRadius: 0,
borderWidth: 1,
data: []
datalabels: {
display: false
}
};
var gadd_dataset = {
label: "GADD SMP SEK",
borderColor: '#001F5B',
fill: false,
pointRadius: 0,
borderWidth: 1,
data: [],
datalabels: {
display: false
}
};

Chart.js move x axis labels to the right

I'm using the latest chart.js to draw a simple histogram.
The histogram is fine but I actually need the x labels to be between the borders of every bar like this histogram_right_labels, are there any methods to approach this?
I've tried offsetGridLines: true and offsetGridLines: false, but what they actually did is moving the grid lines and not the labels, unlike what I read about their actual behaviors, I think it might be a conflict in my option settings but I don't know which, any help would be appreciated.
options: {
maintainAspectRatio: false,
layout: {
padding: {
left: 10,
right: 25,
top: 25,
bottom: 0
}
},
scales: {
xAxes: [{
gridLines: {
//display: false,
drawBorder: false,
padding: 20,
offsetGridLines: true
},
ticks: {
beginAtZero: true,
}
}],
yAxes: [{
ticks: {
padding: 10,
},
gridLines: {
color: "rgb(234, 236, 244)",
zeroLineColor: "rgb(234, 236, 244)",
drawBorder: false,
borderDash: [2],
zeroLineBorderDash: [2]
}
}],
},
legend: {
labels: {
boxWidth: 20
},
display: false
},
tooltips: {
backgroundColor: "rgb(255,255,255)",
bodyFontColor: "#858796",
titleMarginBottom: 10,
titleFontColor: '#6e707e',
titleFontSize: 14,
borderColor: '#dddfeb',
borderWidth: 1,
xPadding: 15,
yPadding: 15,
displayColors: false,
intersect: false,
mode: 'index',
caretPadding: 10,
},
}
You can add a second x-axis of type: 'linear' as follows.
{
type: 'linear',
ticks: {
min: 0,
max: labels.length,
stepSize: 1,
callback: (v, i) => i == 0 ? '' : labels[i - 1]
}
}
Note that I use a ticks callback method in order to provide the desired tick label at given index.
Then you should also hide the grid lines and ticks of the default x-axis.
{
gridLines: {
display: false
},
ticks: {
display: false
}
}
Please take a look at below runnable sample code and see how it works.
const labels = ['4.80', '9.60', '14.40', '19.20', '24.00', '28.80'];
new Chart(document.getElementById('myChart'), {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: "My Dataset",
data: [4, 8, 5, 7, 2, 4],
backgroundColor: 'orange',
categoryPercentage: 1,
barPercentage: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
gridLines: {
display: false
},
ticks: {
display: false
}
},
{
type: 'linear',
ticks: {
min: 0,
max: labels.length,
stepSize: 1,
callback: (v, i) => i == 0 ? '' : labels[i - 1]
}
}
]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<canvas id="myChart" height="90"></canvas>
you can use this to put the tooltips to the right. Possibilities are top, left, right and bottom
options: {
title: {
display: true,
position: 'right'
}
}

How can I show chartjs datalabels only last bar?

I need to show the last bar value only. like this image:
I try this code but it shows all values.
var dataX = {
labels: [['Personne', 'seule'], ['Couple sans', 'enfant'], ['Couple avec', 'enfant(s)'], ['Famille', 'monoparentale'], 'Autres'],
datasets: [{
label: 'Data 1',
data: [33,28,25,8,2.5],
backgroundColor: '#00BBF1',
borderWidth: 0
},
{
label: 'Data 2',
data: [29,30,30,8,2],
backgroundColor: '#3CC6F4',
borderWidth: 0
},
{
label: 'Data 3',
data: [41,22,22,11,3],
backgroundColor: '#92D9F8',
borderWidth: 0
}]
};
var optionsX = {
tooltips: {
enabled: false
},
responsive: true,
maintainAspectRatio: false,
legend: false,
scales: {
xAxes: [{
gridLines : {
color: "#fff"
},
}],
yAxes: [{
gridLines : {
display : false
},
ticks: {
min: 0,
max: 50,
stepSize: 10,
callback: function(value) {
return value + "%"
},
}
}]
},
plugins: {
datalabels: {
color: '#59595B',
font: {
weight: 'bold',
size: 14,
},
align: 'end',
anchor: 'end',
formatter: function(value, context) {
return value +'%';
}
}
},
};
var ctx = document.getElementById('chart-one');
var myChart = new Chart(ctx, {
type: 'bar',
data: dataX,
options: optionsX
});
You can change the plugins.datalabels.formatter function as follows:
plugins: {
...
datalabels: {
formatter: (value, context) => context.datasetIndex == 2 ? value + '%' : ''
}
}
Please take a look at your amended code below and see how it works.
var dataX = {
labels: [
['Personne', 'seule'],
['Couple sans', 'enfant'],
['Couple avec', 'enfant(s)'],
['Famille', 'monoparentale'], 'Autres'
],
datasets: [{
label: 'Data 1',
data: [33, 28, 25, 8, 2.5],
backgroundColor: '#00BBF1',
borderWidth: 0
},
{
label: 'Data 2',
data: [29, 30, 30, 8, 2],
backgroundColor: '#3CC6F4',
borderWidth: 0
},
{
label: 'Data 3',
data: [41, 22, 22, 11, 3],
backgroundColor: '#92D9F8',
borderWidth: 0
}
]
};
var optionsX = {
tooltips: {
enabled: false
},
responsive: true,
maintainAspectRatio: false,
legend: false,
scales: {
xAxes: [{
gridLines: {
color: "#fff"
},
}],
yAxes: [{
gridLines: {
display: false
},
ticks: {
min: 0,
max: 50,
stepSize: 10,
callback: function(value) {
return value + "%"
},
}
}]
},
plugins: {
datalabels: {
color: '#59595B',
font: {
weight: 'bold',
size: 14,
},
align: 'end',
anchor: 'end',
formatter: (value, context) => context.datasetIndex == 2 ? value + '%' : ''
}
},
};
var ctx = document.getElementById('chart-one');
var myChart = new Chart(ctx, {
type: 'bar',
data: dataX,
options: optionsX
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
<canvas id="chart-one"></canvas>

Chart.js label and point getting cutoff on the right

It seems as though the last date label is getting cutoff on my chart here in chart.js. There should be a data point for 2018.
When researching it I've seen it suggested to add layout padding.
I tried that but it disables the chart entirely. Anyone have an alternative solution or an idea on why my layout padding does not work?
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: dollar.years,
datasets: [
{label: 'Cdn dollar in cents',
data: dollar.vals,
borderColor: 'rgb(153,222,101)',
backgroundColor: 'rgb(153,222,101, 0.2)',
pointRadius: 0,
borderWidth: 6,
}]
},
options: {
responsive: true,
title: {
display: false
},
legend: {
display: false
},
labels: {
padding:1
},
scales: {
yAxes: [{
ticks: {
min: 0,
max: 5,
stepSize: 1
}
}],
xAxes: [{
type: "time",
time: {
unit: "year",
tooltipFormat: "YYYY"
},
ticks: {
display: true,
labelOffset: -1,
maxTicksLimit: 5,
drawOnChartArea: false,
autoSkip: false,
maxRotation: 0,
minRotation: 0,
padding: 5
},
}],
}
}
});
}
The option layout.padding work as below code snippet illustrates. You however need to carefully choose the values (number of pixels) in order to not completely hide the chart area.
I would however rather define xAxes.ticks.max to make sure the tick for 2018 is shown even if data would be available up to 2017 only.
const years = [];
const vals = [];
for (let year = 1968; year <= 2018; year++) {
years.push(year.toString());
vals.push(Math.floor(Math.random() * 3) + 1);
}
var myChart = new Chart(document.getElementById("myChart"), {
type: 'line',
data: {
labels: years,
datasets: [{
label: 'Cdn dollar in cents',
data: vals,
borderColor: 'rgb(153,222,101)',
backgroundColor: 'rgb(153,222,101, 0.2)',
pointRadius: 0,
borderWidth: 6
}]
},
options: {
responsive: true,
layout: {
padding: {
left: 0,
right: 100,
top: 0,
bottom: 0
}
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
min: 0,
max: 4,
stepSize: 1
}
}],
xAxes: [{
type: "time",
time: {
parser: 'YYYY',
unit: "year",
tooltipFormat: "YYYY"
},
ticks: {
max: "2018",
maxTicksLimit: 5,
maxRotation: 0
}
}]
}
}
});
canvas {
max-width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<canvas id="myChart" width="600" height="400"></canvas>

chart.js bar chart time axis tooltip issue

I am plotting bar chart with time axis, X-Axis unit is 'day' and ticks will be 30 day apart.With this tooltip is not displaying. I am using 2.0 beta2 version. Its a 1 year graph with random time sample data. UserCallBack function skips ticks for 30 days.
Any suggestions why tool tip is not displaying?
var canvas = document.getElementById('myChart');
var labelsArray = ["2017/06/09 00:00:00", "2017/07/05 00:00:00"];
var data = {
labels: labelsArray,
datasets: [{
label: "My First dataset",
data: [10, 50],
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 2,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
}]
};
var xAxesConfig = [{
type: "time",
categoryPercentage: 0.1,
barPercentage: 0.2,
time: {
displayFormat: 'MMM-DD',
format: 'YYYY/MM/DD HH:mm:SS',
unit: 'day',
min: '2016/09/12 17:00:00',
max: '2017/09/12 17:00:00'
},
scaleLabel: {
display: true,
labelString: 'Time',
fontSize: 14,
fontStyle: "bold"
},
ticks: {
maxRotation: 0,
autoSkip: false,
userCallback: function(value, index, values) {
return (index % 30 == 0) ? value : null;
//return value;
}
}
}];
var yAxesConfig = [{
position: 'left',
gridLines: {
display: true
},
ticks: {
maxTicksLimit: 5,
suggestedMin: 0,
suggestedMax: 10
},
scaleLabel: {
display: true,
labelString: 'Value',
fontSize: 14,
fontStyle: "bold"
}
}];
var option = {
scales: {
yAxes: yAxesConfig,
xAxes: xAxesConfig,
}
};
var myBarChart = Chart.Bar(canvas, {
data: data,
options: option
});