Control which lines have points? - javascript

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.

Related

Change the color of one point only in a Flot line chart

Is there a way to change the color of one point only (the last) in a line plot?
Hhint: The number of points which I use is 4.
Part of current code is the following:
var Arr_data = [[]];
...
var plot1 = {
series: {
lines: {
show: false,
fill: 1,
},
splines: {
show: true,
tension: 0.4,
lineWidth: 2,
fill: 0.1,
},
points: {
radius: 8,
lineWidth: 1,
show: true,
symbol: "circle",
fillColor: customColorVar
},
...
$.plot($("#chartID"), [ Arr_data ], plot1);
That is not possible with the normal options. What you can do is copy only the last data point to a second data series and for that data series use the different color. This should draw over the point from the first data series. If there are problems with this you could go one step further and generate three data series:
One with all data points for a line,
one with all data points but the last for the points in the normal color and
one with only the last data point for the other color.

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.

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

Chart.js - Where to put global chart configuration?

I am trying to set up a Chart.js line graph with the following code. Where in this do I place the Chart.defaults.global = {} or Chart.defaults.global.responsive = true; code?
Chart.js docs can be found here: http://www.chartjs.org/docs/
<!-- Chart.js -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.min.js"></script>
<script>
var ctx = document.getElementById("myChart").getContext("2d");
var data = {
labels: ["Week 1", "Week 2", "Week 3", "Week 4", "Week 5", "Week 6", "Week 7"],
datasets: [
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [86, 74, 68, 49, 42]
}
]
};
var options = {
...
};
var myLineChart = new Chart(ctx).Line(data, options);
</script>
There are two ways to accomplish what you're looking for. This way
var myLineChart = new Chart(ctx).Line(data, options);
var options = Chart.defaults.global = {
responsive: true,
maintainAspectRatio: true
};
or, this way
var myLineChart = new Chart(ctx).Line(data, {
responsive: true,
maintainAspectRatio: true
});
However, to make it responsive you'll have to add some extra CSS
canvas{
width: 100% !important;
height: auto !important;
}
so there's no need for inline CSS
Working demo
In accordance with the comment of #JustinXL below and the latest version of Chart.js there's no need for extra CSS, so check out the updated version.
Updated demo
You could set the options of your chart, but you can also set the global (as you asked) to avoid setting this specific property for each chart you want to instantiate.
You just have to set
Chart.defaults.global.elements.responsive = true;
before instantiating the chart, in your case, before
var myLineChart = new Chart(ctx).Line(data, options);
(P.S.: Chartjs V2)

Categories

Resources