How to assign a logarithmic scale to y axis in chart.js? - javascript

var data1 = {
labels: JSON.parse('<?php echo JSON_encode($bioc_months);?>'),
datasets: [{
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
data: 1000,
900,
90,
200,
1020
}, {
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
data: 600,
456,
20,
2,
900
]
};
var opt1 = {
canvasBordersWidth: 3,
canvasBordersColor: "#205081",
scaleOverride: true,
scaleSteps: 6,
scaleStepWidth: log2,
scaleStartValue: 0,
scaleLabel: "<%=value%>",
legend: true,
inGraphDataShow: true,
annotateDisplay: true,
inGraphDataShow: false,
annotateDisplay: true,
animationEasing: "easeOutBounce",
graphTitleFontSize: 18
};
var myBarChart1 = new Chart(ctx1).Bar(data1, opt1);

You can assign logarithmic scale to y-axis as below:
yAxes: [{
scaleLabel: {
display: true,
labelString: 'LABEL',
},
type: 'logarithmic',
position: 'left',
ticks: {
min: 0.1, //minimum tick
max: 1000, //maximum tick
callback: function (value, index, values) {
return Number(value.toString());//pass tick values as a string into Number function
}
},
afterBuildTicks: function (chartObj) { //Build ticks labelling as per your need
chartObj.ticks = [];
chartObj.ticks.push(0.1);
chartObj.ticks.push(1);
chartObj.ticks.push(10);
chartObj.ticks.push(100);
chartObj.ticks.push(1000);
}
}]

As #user2722127 pointed out, the essence is to put the type on "logarithmic".
If you only take care of that, then you will end up with awkward labels in scientific format (e.g. 200000 = "2e5"). I personally prefer them a little more human.
So, the callback method actually converts numeric data values to string label values.
Note: the callback will not be called for all values in your dataset. It will just be called for the auto-generated ticks. In my case that was enough. Nevertheless, there may be too much labels. So to limit the number of labels, I simply return null for all unwanted label values.
yAxes: [{
type: 'logarithmic',
ticks: {
min: 1,
max: 1000000,
callback: function (value, index, values) {
if (value === 1000000) return "1M";
if (value === 100000) return "100K";
if (value === 10000) return "10K";
if (value === 1000) return "1K";
if (value === 100) return "100";
if (value === 10) return "10";
if (value === 1) return "1";
return null;
}
}
}]
Note: the screenshot above shows a chart with a 0-point on its scale. That's actually incorrect. As you can see in the above source code, I later modified the minimum value to be 1. I had to do so, because in later version of chart.js charts actually were seriously messed up and sometimes drawn underneath the chart. And it was all due to a 0-tick. Actually from a mathematical point of view, a logarithmic scale cannot really have a 0-tick. So, it makes more sense to just start at 1 or 0.001 for example. But not 0.
EDIT:
The following is not strictly necessary, but may possibly improve performance.
If you want more control on the created ticks, you can provide an afterBuildTicks property. ( Which is very similar to what is provided in the answer of #user2722127 .) In this example, it just replaces the content of the ticks array of the chart object with different ticks.
afterBuildTicks = (chartObj) => {
const ticks = [1, 10, 100, 1000, 10000, 100000, 1000000];
chartObj.ticks.splice(0, chartObj.ticks.length);
chartObj.ticks.push(...ticks);
}
You just add this function as a property to the yAxis element, along with the other properties.
yAxes: [{
type,
ticks,
afterBuildTicks
}]

http://www.chartjs.org/docs/#scales-logarithmic-scale
Logarithmic Scale
The logarithmic scale is use to chart numerical data. It can be placed
on either the x or y axis. As the name suggests, logarithmic
interpolation is used to determine where a value lies on the axis.

Related

I have 10 points inn x-axis, ranging [-25,-20,,-15,-10,0,10,20,30,40,50]. But I want my line chart to start from -15 of x-axis. How we can achieve?

I have 10 points inn x-axis, ranging [-25,-20,-10,0,10,20,30,40,50]. But I want my line chart to start from -15 of x-axis. How we can achieve?
Below is the code i tried with suggestedmin and suggestedmax but it didnt worked.
Please suggest some way to achieve this
export class CgChartComponent {
lineChartData: ChartDataSets[] = [
{ data: [3145000, 3430001, 1499998, 1700000, 3515340, 2480011], label: 'ABC', lineTension: 0, },
];
lineChartLabels: Label[] = ['-25','-20','-15', '-10', '0', '10', '20', '30','40','50' ];
lineChartOptions = {
responsive: true,
responsiveAnimationDuration: 30,
legend: {
position: 'bottom'
},
scales: {
xAxes: [{
ticks: {
suggestedMin: -15,
suggestedMax: 40
}
}]
}
};
lineChartColors: Color[] = [
{
borderColor: 'black',
},
];
lineChartLegend = true;
lineChartPlugins = [];
lineChartType = 'line';
}
Try to use min and max instead of suggestedMin and suggestedMax as follows:
xAxes: [{
ticks: {
min: -15,
max: 40
}
}]
From Chart.js documentation
Axis Range Settings
The suggestedMax and suggestedMin settings only change the data values that are used to scale the axis. These are useful for extending the range of the axis while maintaining the auto fit behaviour.
Tick Configuration
min: User defined minimum value for the scale, overrides minimum value from data.
max: User defined maximum value for the scale, overrides maximum value from data.
UPDATE
The problem is probably that the labels are strings but min and max are defined as numbers. This can be solved in two different ways.
Either you transform the labels into numbers or you define min and max as follows:
xAxes: [{
ticks: {
min: '-15',
max: '40'
}
}]

Chart.js automatic scaling

I've been testing out chart.js for maybe including it in a project. I just have one smallish issue with it. It doesn't scale some datasets properly. I found somewhat similar questions here in SO, but nothing really that would solve my issue.
So this is what my chart looks like with some datasets:
For some reason, the max values (2.2) look ugly as hell. The reason is, that the dataset has a set of three duplicate values in this case (2.2, 2.2, 2.2). I would like there to be some room on top of this series, so that it would look a bit more reasonable.
How do you properly add "padding" on top the the series line? I would like a solution where I could rely on chart.js to find out the max value, and then maybe update that with some padding on the scale(like x + 10). Issue is, that I cant just hard code the min max values, because I can have over 200 different values that can be selected, and they can vary A LOT in scale.
Here is how I render the chart for now:
return new Chart(context, {
type: 'line',
data: {
labels: labels.data,
datasets: dataSets
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
ticks: {
beginAtZero: false
},
yAxes: [{
ticks: {
beginAtZero: false
},
id: 'A',
type: 'linear',
position: 'left',
}, {
ticks: {
beginAtZero: false
},
display: displayBAxis,
id: 'B',
type: 'linear',
position: 'right',
}]
}
}
});
This may not be the cleanest way but you can play with it as you see fit.
In short, you need to create a function that finds the max value out of all your dataSets arrays and in yAxes.ticks set max to that functions return value.
More details below
Referencing here first:
data:{
labels: labels.data,
datasets: dataSets //talking about this first
}
Create a function that will go through these arrays and get the max of all arrays. I did it using this but you can do it better I'm sure:
function getMax(){
var max = 0;
dataSets.forEach(function(x, i){
max = Math.max(max, Math.max.apply(null, x.data));
});
return max + 2;
}
Then in your return in yAxes you should be able to have:
ticks: {
beginAtZero: false,
max: getMax()
},
You can find the min and max of your dataset, then add/subtract a percentage of the difference (range).
For example, say you use 1% of the range.
[0.1, 0.2, 0.5] gives (1%)x(0.5-0.1)=0.004, so [min,max]=[0.096,0.504].
[1500, 1800, 3500, 3600] gives (1%)x(3600-1500)=21, so [min,max]=[1479,3621].

Setting Canvas Limits Over the Existing Dataset Values

I've got a little problem with html5 canvas. I've got a couple of line charts made but they have a problem with maximum grid values (sort of field limits inside the canvas itself). The chart is building from a dataset coming from the database and only through these values.
The example: sample chart
As you can see here, the above limit is 5.55, and the question is how to change that to a bigger value (for example, using a percentage of such maximum value or something so that other charts' offsets would match as well)?
The code:
$('#graf_' + i + '').html('<canvas id="lineChart' + i + '" width="' + $(".graf").width() + '" height="200"></canvas>');
var lineData = {
labels: data["headers"],
datasets: [{
label: data["rates"][i]["VltName"],
fillColor: "transparent",
strokeColor: data["rates"][i]["VltColor"],
pointColor: data["rates"][i]["VltColor"],
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: getRatesArr
}]
};
var lineOptions = {
scaleShowGridLines: true,
scaleGridLineColor: "rgba(0,0,0,.05)",
scaleGridLineWidth: 1,
bezierCurve: false,
pointDot: true,
pointDotRadius: 4,
pointDotStrokeWidth: 1,
pointHitDetectionRadius: 20,
datasetStroke: true,
datasetStrokeWidth: 2,
datasetFill: true
};
var ctx = document.getElementById("lineChart" + i).getContext("2d");
var myNewChart = new Chart(ctx).Line(lineData, lineOptions);
Hope my explanation is not too vague. Thanks in advance!
If you update to the latest Chart.js version (currently v2.6.0), you can use the max tick configuration option to set the max number to display on the axis:
options: {
scales: {
yAxes: [{
ticks: {
max: yourMaxNum
}
}]
}
}
If you want to set yourMaxNum to the largest number in all your dataset arrays, simply use the JavaScript Math.max() method to determine this number, and set the above chart config option to this number when you create all your line charts.
The Chart.js documentation lists additional tick configuration options that you might also find useful.

Cannot change chart.js color fill or y axes

I am trying to make a real time graph using chart.js, but I cannot seem to change the color fills.
<script type="text/javascript">
var canvas = document.getElementById('updating-chart'),
ctx = canvas.getContext('2d'),
startingData = {
labels: ["A", "B", "C", "D"],
datasets: [
{
label: "Product A",
fillColor: "rgba(206, 70, 90, 1)",
strokeColor: "rgba(220,220,220,0.8)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
data: [65, 59, 80, 81],
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
min: 0,
max: 10
}
}]
}
}
}
]
};
var myLiveChart = new Chart(ctx,{
type: 'bar',
data: startingData,
responsive: true,
maintainAspectRatio: true
});
setInterval(function(){
// Get a random index point
var indexToUpdate = Math.round(Math.random() * startingData.labels.length);
// Update one of the points in the second dataset
myLiveChart.data.datasets[0].data[indexToUpdate] = Math.random() * 100;
myLiveChart.update();
}, 500);
</script>
I've clearly changed the axes and set the y to a maximum, but it still overflows and keeps dynamically changing the axes length. How do I fix this?
Also the color still seems to be grey for the first bar, even though I changed the rgba values. Help?
refer the below link for changing the colors.try background-color.If you share the fiddle it will help.
http://www.chartjs.org/docs/#chart-configuration-colors
Add below code in your datasets array. Color will change.
backgroundColor:"rgba(206, 70, 90, 1)"
https://jsfiddle.net/Smita31Jain/4zpuxvke/
For overflow and dynamically changing axes length issue, take out options property object code from startingData object's dataset array and add it to myLiveChart chart instance. Refer below jsfiddle
https://jsfiddle.net/Smita31Jain/zzpkxg3k/
Hope this is what you are looking for.

Remove the vertical line in the chart js line chart

I am using Chart.js to generate maps and have customised it to a good extent. But I am not able to remove the vertical grid line no matter what. Has anyone come across a situation like this? Help much appreciated.
JavaScript
var ChartDataHome = {
labels: ["", "NOV", "DEC", "JAN", "FEB"],
datasets: [{
strokeColor: "rgba(255.255,255,1)",
pointColor: "rgba(159,209,154,1)",
pointStrokeColor: "rgba(255,255,255,1.00)",
data: [4.5, 8.8, 7.5, 9.5, 7.8, 9]
}]
};
var step = 2;
var max = 10;
var start = 0;
ChartOptionsHome = {
scaleLabel: "<%= value + ' K ' %>",
pointDot: false,
bezierCurve: false,
scaleOverride: true,
scaleSteps: 10,
scaleSteps: Math.ceil((max - start) / step),
scaleStepWidth: step,
scaleStartValue: start,
scaleShowGridLines: true,
scaleGridLineWidth: 0,
scaleGridLineColor: "rgba(0,0,0,0.1)",
datasetFill: false,
animation: true,
animationSteps: 60,
scaleFontColor: "#ffffff",
scaleFontSize: 14,
scaleLineColor: "rgba(255,255,255,1)",
datasetStrokeWidth: 6,
responsive: true,
}
if ($("#chartHome")[0]) {
DrawTheChart(ChartDataHome, ChartOptionsHome, "chartHome", "Line");
}
The following applies to Chart.js 2.*.
If you only have one x-axis, whether the vertical grid lines (that are related to this x-axis) are displayed or not, is specified by the boolean value of options.scales.xAxes[0].gridLines.display. To be more precise, the following chart options disable the display of vertical grid lines for the single x-axis case.
options : {
scales : {
xAxes : [ {
gridLines : {
display : false
}
} ]
}
}
There's a new global option that was released with the new version of Chart.js two days ago.
var options = {
scaleShowVerticalLines: false
}
The Above answers seem outdated since they did not work in ChartJs 3.4.1 (probably lower versions as well) for me.
You can now use the following:
options: {
scales: {
x: {
grid: {
display: false
}
},
}
}
It's self-explanatory, but to remove horizontal lines, you can replace the x with y.
options : {
scales: {
yAxes: [{
gridLines: {
lineWidth: 0,
color: "rgba(255,255,255,0)"
}
}]
}
};
Charts.js v2.0
try "scaleShowGridLines" : false,
I think you can seperate x and y axis.
axes: {
xaxis: {
ticks: ticks,
tickOptions: {showGridline:false}
},
yaxis: {
tickOptions: {showGridline:true}
}
}
Hope this can help you.
Simply write
options:{
grid:{
show: false
},
}
It will solve your problem

Categories

Resources