Setting Canvas Limits Over the Existing Dataset Values - javascript

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.

Related

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.

Use data from database in Chart.js/Rails

I want to show a line chart on my "Weights" index page with Chart.js in my Rails app (a weight loss app). I have a table that holds a user's weight (as "kilograms") for each day (as "day"). I am able to show a line chart, however, but only with static data - not with the data from my Weights table.
What I want to do now is to have "day" on the x-axis and "kilograms" on the y-axis.
How can I achieve this? And as I just started coding few months ago: how should the code look like?
Thx a lot.
This is the code from my weights index.html.erb:
<canvas id="myChart" width="400" height="200"></canvas>
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["day 1", "day 2", "day 3", "day 4", "day 5", "day 6"],
datasets: [{
label: 'My Weight',
data: [82.4, 79.6, 79.3, 78.4, 77.5, 75.1],
backgroundColor: [
'rgba(0, 0, 0, 0.1)',
],
borderColor: [
'rgba(0,0,0,0.9)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:false
}
}]
}
}
});
</script>
The main thing that had me stuck forever was that Chart.js relies on calling its tooltiptemplate with <% however this would then be interpreted by ERB and cause a problem. The workaround is adding another % which tells erb not to interpret the tags it otherwise would have. That's not very well documented but what are you going to do. As for the rest, in your view-page.html.erb file you want to add the chart scripts at the bottom:
Set your timeline X-Axis (I'll show you how to load it dynamically but this could be static if you want in which case just enter them directly into the timeline array):
<script type="text/javascript">
$(function() {
var lineData = {
<% timeline = []
datapoints = []
#workout.each do |workout|
timeline << workout.day
datapoints << workout.weight
end
%>
//The "raw" method is needed to stop the auto escaping of the output. Test this out in your console and you will notice the output is formatted like "[\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\"]" This escaping of quotes causes errors in js...
labels: <%= raw timeline.to_json %>,
datasets: [{
label: "Weight Gain/Loss",
fillColor: "rgba(26,179,148,0.5)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#127A65",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: <%= raw datapoints.to_json %>,
}]
};
If you want to set some options remember to use the <%% tag for tooltips!
var lineOptions = {
scaleOverride : true,
tooltipTemplate: "<%%if (label){%>(<%%=label%>) <%%}%><%%= value %> pounds",
};
//NOTE THE ABOVE TOOLTIP REQUIRES A SECOND % SIGN ON OPENING TAGS SO THAT IS IS TAKEN LITERALLY AND NOT INTERPRETED BY RAILS ERB!!!!!!!!
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).Line(lineData, lineOptions);
});
</script>
I, too, was struggling with getting this to work on Rails, but I discovered that I did not have to use the Rails template escape characters that chart.js says that you do. In my case (needing to show a zero in the label when the value is set to 0.1), this is what I did:
tooltipTemplate: function(context){
var labelVal = (context.value == '0.1')? '0' : context.value;
var newLabel = context.label + ': ' + labelVal;
return newLabel;
}

Control which lines have points?

With Chart.js, you can set in the options of the graph to show points or not:
pointDot: true,
I have a graph with three static lines and one line that shows some fluctuations. I'd like the straight lines not to have points but the fluctuation line show the points. Is there a setting somewhere on the line that I can set the point size to nothing?
** Edit **
Each line is its own set of data configured like this:
datasets: [
{
label: "Cycle Time Per Last Piece",
strokeColor: "red",
fillColor: "red",
pointHighlightFill: "red",
data: [#foreach (var item in Model.DataPoints) {
#(Model.ExpectedCycleTimePerPart * 1.20M)#:,
}]
},
{
label: "Expected Cycle Time Per Part",
strokeColor: "black",
pointHighlightFill: "black",
data: [#foreach (var item in Model.DataPoints) {
#Model.ExpectedCycleTimePerPart#:,
}]
}
The pointDot option drives the display property, so you can do something like
myChart.datasets[0].points[2].display = false;
where myChart is your chart object.

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

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.

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