Chart.js how to use scriptable options - chart.js

I am migrating chart.js to 3.x as per the migration guide.
https://www.chartjs.org/docs/master/getting-started/v3-migration/
I am trying to set the xAxis zeroLineColor to "#FFFFFF" and I want to have the Grid line color as "#00FFFF" but as per the chart.js migration document document scales.[x/y]Axes.zeroLine* options of axes were removed. Use scriptable scale options instead.
I am not sure how to use scriptable scale options for setting the xAxis line zero to white.
Update:
Working example:
https://jsfiddle.net/g4vq7o2b/2/

In order to obtain different colors for the grid's zero line, you could define an array of colors for the option gridLines.color.
gridLines: {
drawBorder: false,
color: ["#FFFFFF", "#00FFFF", "#00FFFF", "#00FFFF", "#00FFFF"]
}
Since gridLines.color is a scriptable options, it also accepts a function which is invoked with a context argument for each of the underlying data values as follows:
gridLines: {
drawBorder: false,
color: context => context.tick.value == 0 ? "#FFFFFF" : "#00FFFF"
}
Please take a look at below runnable code and see how it works.
new Chart(document.getElementById("myChart"), {
type: "line",
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My Dataset",
data: [2, 3, 1, 4, 2, 4, 2],
fill: false,
backgroundColor: "rgba(0, 255, 0, 0.3)",
borderColor: "rgb(0, 255, 0)"
}]
},
options: {
scales: {
y: {
min: 0,
ticks: {
stepSize: 1
},
gridLines: {
drawBorder: false,
color: context => context.tick.value == 0 ? "#FFFFFF" : "#00FFFF"
}
},
x: {
gridLines: {
drawBorder: false,
color: context => context.tick.value == 0 ? "#FFFFFF" : "#00FFFF"
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.0-beta/chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Using chart_v3.7.0.js cartesian time axis, for me, configuring zeroline and other gridlines works, using scriptable options.
Apply property for "context.tick.value == 0" (=baseline)
like:
...
options: {
scales: {
x: {
gridLines: {
color: "#00ff00",
},
ticks: { font: { size: 30 },
maxRotation: 90,
minRotation: 90,
},
type: 'time',
time: {
/*tooltipFormat: "DD.MM hh:mm",*/
displayFormats: {
minute: 'HH:mm',
hour: 'HH:mm',
day: 'dd.MMM',
}
},
},
y: {
grid: {
color: (line) => (line.index === 0 ? 'red' : 'rgba(0, 0, 0, 0.1)') //color of lowest horizontal grid line
color: context => context.tick.value == 0 ? "#FFFFFF" : "#00FFFF", // zero-line baseline color
lineWidth: context => context.tick.value == 0 ? 3 : 1, // zero-line baseline width
},
position: 'right', // show axis on the right
title: { display: true,
rotation: 0,
text: "°C", },
},
},

Related

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'
}
}

Chartjs: How to offset ticks on radarchart?

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}';
},

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>

How to display axis borders only (no grid lines) in chartjs?

So I only want to show the axes border lines - and hide the grid lines. This is using the latest version of the chart.js package (2.9.3) and I have replicated my issue in a simplified Codepen shown below:
var myChart = new Chart(ctx, {
type: 'scatter',
data: {
labels: [4, 0],
datasets: [{
data: [
{ group_name: "Group A", x: 4, y: 25 },
{ group_name: "Group B", x: 0, y: 0 },
],
}],
},
options: {
legend: { display: false },
scales: {
yAxes: [ {
type: 'logarithmic',
scaleLabel: { display: true, labelString: 'Active %', fontSize: 15 },
position: 'left',
gridLines: { display: false, drawBorder: true },
ticks: {
min: 0,
max: 50,
maxTicksLimit: 4,
padding: 10,
callback: value => `${value.toLocaleString()}%`,
},
} ],
xAxes: [ {
type: 'logarithmic',
position: 'bottom',
scaleLabel: { display: true, labelString: 'User Count', fontSize: 15 },
gridLines: { display: false, drawBorder: true },
ticks: {
min: 0,
maxTicksLimit: 6,
padding: 10,
callback: value => value.toLocaleString(),
},
} ],
},
}
});
Any help or insight is appreciated; the settings I'd expect to work from the docs don't seem to be working.
You can put this options in gridline properties:
xAxes: [{
gridLines: {
display: true,
drawBorder: true,
drawOnChartArea: false
}
}]
Source: https://www.chartjs.org/samples/latest/scales/gridlines-display.html
Solved it (sort of). When I downgrade to chart.js 2.8.0 the chart borders now display as expected. With 2.9.3 the borders were not showing at all, regardless of chart type.
gridLines: { drawBorder: true, lineWidth: 0 }

Is there a way to create a chart with only a single axis?

I'm trying to create a "chart" where I only want to show the x-axis. Basically I'm trying to create visualization of a range (min-max) and a point that sits in between like:
I'm unable to find any resources online on how to make this, or what this type of plot is even called. If anyone could help out, that would be awesome!
This is straightforward to achieve through styling a line chart appropriately and using linear x- & y-axes with points defined via x and y coordinates.
By keeping y at 0 you can assure the points all appear in the same horizontal position.
The example below gets the visual result you want, but you'll probably want to disable tooltips for the 'fake' x-axis line via a callback:
let range = {
min: 0,
max: 100
},
pointVal = 65;
new Chart(document.getElementById("chart"), {
type: "line",
data: {
labels: ["", "", ""],
datasets: [{
pointBackgroundColor: "green",
pointRadius: 10,
pointHoverRadius: 10,
pointStyle: "rectRot",
data: [{
x: pointVal,
y: 0
}]
}, {
// this dataset becomes the 'fake' x-axis line.
pointBackgroundColor: "black",
borderColor: "black",
data: [{
x: range.min,
y: 0
},
{
x: range.max / 2,
y: 0
},
{
x: range.max,
y: 0
}
]
}]
},
options: {
legend: {
display: false
},
hover: {
mode: "point"
},
layout: {
padding: {
left: 10,
right: 10,
top: 0,
bottom: 0
}
},
scales: {
xAxes: [{
type: "linear",
display: false
}],
yAxes: [{
display: false
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<div style="width:200px">
<canvas id="chart"></canvas>
</div>