Draw a mathematical function in chartjs - javascript

I'd like to know if it's possible to draw this function in chart js :
And have something that look like :
For now, using the solution given in an other post I have this result :
But as you can see, the parabola part of the graph extends too far on the x-axis and therefore does not look like the expected result..
I'm using this code :
const data = {
labels: labels,
datasets: [
{
function: function (x) {
if (x <= Ec2) {
return fck * (1 - Math.pow(1 - x / Ec2, n));
} else {
return fck;
}
},
borderColor: 'red',
data: [],
fill: false,
pointRadius: 0,
},
],
};
Chart.pluginService.register({
beforeInit: function (chart) {
if (Ec2 > 0) {
for (let i = 0; i <= Ec2; i += Ec2 / 5) {
labels.push(i.toFixed(1));
}
}
if (Ecu2 > 0) {
labels.push(Ecu2);
}
var data = chart.config.data;
for (var i = 0; i < data.datasets.length; i++) {
for (var j = 0; j < data.labels.length; j++) {
var fct = data.datasets[i].function,
x = data.labels[j],
y = fct(x);
data.datasets[i].data.push(y);
}
}
},
});

I think your code is just right, but there are not enough data points in the X axis and therefore the shape of the function looks like a totally different function.
Here is the same code with more X axis data points:
var Ec2 = 5
var fck = 2
var ctx = document.getElementById("myChart");
var data = {
labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
datasets: [{
label: "f(x)",
function: function(x) {
if (x <= Ec2) {
return fck * (1 - Math.pow(1 - x / Ec2, 2));
} else {
return fck;
}
},
borderColor: "rgba(75, 192, 192, 1)",
data: [],
fill: false
}]
};
Chart.pluginService.register({
beforeInit: function(chart) {
var data = chart.config.data;
for (var i = 0; i < data.datasets.length; i++) {
for (var j = 0; j < data.labels.length; j++) {
var fct = data.datasets[i].function,
x = data.labels[j],
y = fct(x);
data.datasets[i].data.push(y);
}
}
}
});
var myBarChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
title: {
display: true
},
legend: {
position: 'bottom'
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.min.js"></script>
<canvas id="myChart"></canvas>
I simply added more label entries with so that data.labels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].

Related

Chart js animating a line while changing x-axis labels

I achieved animating a plot using Jukka Kurkela example here.
Now I am having trouble customizing this plot further.
Logic of the custom plot
The plot starts animating with the x-axis labels being 0-20. When the plot reaches 20 then update the x-axis to be 20-40. Increment i or 20 until the x-axis reach its limit.
How to apply the logic above to the Example below?
// Generating data
var data = [];
var prev = 100;
for (var i=0;i<200;i++) {
prev += 5 - Math.random()*10;
data.push({x: i, y: prev});
}
var delayBetweenPoints = 100;
var started = {};
var ctx2 = document.getElementById("chart2").getContext("2d");
var chart2 = new Chart(ctx2, {
type: "line",
data: {
datasets: [
{
backgroundColor: "transparent",
borderColor: "rgb(255, 99, 132)",
borderWidth: 1,
pointRadius: 0,
data: data,
fill: true,
animation: (context) => {
var delay = 0;
var index = context.dataIndex;
if (!started[index]) {
delay = index * delayBetweenPoints;
started[index] = true;
}
var {x,y} = index > 0 ? context.chart.getDatasetMeta(0).data[index-1].getProps(['x','y'],
true) : {x: 0, y: 100};
return {
x: {
easing: "linear",
duration: delayBetweenPoints,
from: x,
delay
},
y: {
easing: "linear",
duration: delayBetweenPoints * 500,
from: y,
delay
},
skip: {
type: 'boolean',
duration: delayBetweenPoints,
from: true,
to: false,
delay: delay
}
};
}
}
]
},
options: {
scales: {
x: {
type: 'linear'
}
}
}
});
<div class="chart">
<canvas id="chart2"></canvas>
</div>
<script src="https://www.chartjs.org/dist/master/Chart.js"></script>
Solved it! Instead of incrementing 20 seconds, it is incrementing every 5 seconds ahead of time. Definitely a better experience for the user.
Got help from Rowf Abd's post.
var myData = [];
var prev = 100;
for (var i=0;i<60;i++) {
prev += 5 - Math.random()*10;
myData.push({x: i, y: prev});
}
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
data: [myData[0]],
pointRadius: 0,
fill: false,
borderColor: "black",
lineTension: 0
}]
},
options: {
legend: {
onClick: (e) => e.stopPropagation()
},
title:{
fontColor: 'Black'
},
layout: {
padding: {
right: 10
}
},
scales: {
xAxes: [{
type: 'linear',
ticks: {
}
}],
yAxes: [{
scaleLabel: {
// fontFamily: 'Lato',
fontSize: 19,
fontColor: "Black"
}
}]
}
}
});
var next = function() {
var data = chart.data.datasets[0].data;
var count = data.length;
var xabsmin = 20;
var xabsmax = 60;
var incVar = 5;
data[count] = data[count - 1];
chart.update({duration: 0});
data[count] = myData[count];
chart.update();
if (count < myData.length - 1) {
setTimeout(next, 500);
}
if (data[count].x < xabsmin) {
chart.config.options.scales.xAxes[0].ticks.min = xabsmin - xabsmin;
chart.config.options.scales.xAxes[0].ticks.max = xabsmin;
chart.update();
}
if(data[count].x >= xabsmin && data[count].x < (xabsmax)){
var currentT = parseFloat(data[count].x);
var modDiv = (currentT % incVar);
var tempXMax = (currentT) + (incVar - modDiv);
chart.config.options.scales.xAxes[0].ticks.max = tempXMax;
chart.config.options.scales.xAxes[0].ticks.min = tempXMax - xabsmin;
chart.update();
}
}
setTimeout(next, 500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<canvas id="myChart"></canvas>

How select values from multidimensional array to draw graphics?

have JSON
<c:set var="json_text">
{
"FailedCount":[{"FailedCount_MEAS_VALUE":1,"DATETIME_CURRENT":"12:01"},
{"FailedCount_MEAS_VALUE":0,"DATETIME_CURRENT":"12:02"},
{"FailedCount_MEAS_VALUE":3,"DATETIME_CURRENT":"12:03"},
{"FailedCount_MEAS_VALUE":4,"DATETIME_CURRENT":"12:04"}],
"SucceededCount":[{"SucceededCount_MEAS_VALUE":110},
{"SucceededCount_MEAS_VALUE":120},
{"SucceededCount_MEAS_VALUE":130},
{"SucceededCount_MEAS_VALUE":140}]
}
</c:set>
prepare data
function culcJson() {
var jsonObj = ${json_text};
var VALUES=[];
var n = jsonObj.FailedCount.length, m = 5;
var mas = [];
for (var i = 0; i < m; i++){
mas[i] = [];
for (var j = 0; j < n; j++){
if (i==0) {
mas[i][j] = jsonObj.FailedCount[j].FailedCount_MEAS_VALUE;
}
if (i==1)
{
mas[i][j] = jsonObj.SucceededCount[j].SucceededCount_MEAS_VALUE;
}
if (i==2)
{
mas[i][j] =jsonObj.FailedCount[j].FailedCount_MEAS_VALUE+jsonObj.SucceededCount[j].SucceededCount_MEAS_VALUE;
}
if (i==3)
{
var KPI = jsonObj.SucceededCount[j].SucceededCount_MEAS_VALUE / (jsonObj.SucceededCount[j].SucceededCount_MEAS_VALUE + jsonObj.FailedCount[j].FailedCount_MEAS_VALUE) * 100;
mas[i][j] = +KPI.toFixed(2);
}
if (i==4)
{
mas[i][j] =jsonObj.FailedCount[j].DATETIME_CURRENT;
}
VALUES.push(mas[i][j]);
}}
console.log(mas);
return VALUES;
}
trying to build chart depending KPI from DATETIME
$(function () {
var VALUES;
VALUES=culcJson();
result_newjson.innerHTML = VALUES;
$('#container').highcharts({
chart: {
zoomType: 'x'
},
title: {
text: '${title}'
},
xAxis: {
categories: ["12:01","12:02","12:03","12:04"]
},
yAxis: {
title: {
text: ''
}
},
legend: {
enabled: true
},
plotOptions: {
area: {
fillColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1},
stops: [
[0, Highcharts.getOptions().colors[0]],
[1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
]
},
marker: {
radius: 2
},
lineWidth: 1,
states: {
hover: {
lineWidth: 1
}
},
threshold: null
}
},
series: [
{
name: 'KPI',
data: [99.5,100,98.56,99.99]
}
]
});
});
How to correctly refer to VALUES array to select only the time and KPI instead of static values
categories: ["12:01","12:02","12:03","12:04"] и data: [99.5,100,98.56,99.99]
?

Flot Bar and Line chart [duplicate]

I've made this bar chart http://imageshack.com/a/img901/7186/cnOfhh.png, and the code for it is:
//compute & mark average color
for (var i = 0; i < zdata.length; i++) {
if (zdata[i].TargetTime == null) zdata[i].TargetTime = 0;
if (zdata[i].TimePlayed == null) zdata[i].TimePlayed = 0;
if (zdata[i].TargetTime >= zdata[i].TimePlayed) {
zdata[i]['Color'] = 'green';
} else {
zdata[i]['Color'] = 'red';
}
}
//localsitelist
var element = {
rt: 'D',
Id: rid,
courselist: clist,
selcourseId: selCid,
selcourse: selCname,
cartlist: wData,
selSiteId: lsid,
selsite: sitename,
dataList: zdata
}; //, carts: _mVM.availableCarts()}; //
//if rid exists, is update, else its new
var found = -1;
for (var k = 0; k < document.pvm.rapArray().length; k++) {
if (document.pvm.rapArray()[k].Id() == rid) {
document.pvm.rapArray()[k].update(element);
//build chart data
var values = []; //, series = Math.floor(Math.random() * 6) + 6;
for (var i = 0; i < zdata.length; i++) {
values[i] = {
data: [
[zdata[i].HoleSequence, zdata[i].TimePlayed]
],
color: zdata[i].Color
};
}
//var data = [{ data: [[0, 1]], color: "red" }, { data: [[1, 2]], color: "yellow" },{ data: [[2, 3]], color: "green" }];
BarChart('#ChartD-Overview' + rid, values);
found = 1;
break;
}
}
if (found == -1) {
var rvm = new panelViewModel(element);
document.pvm.rapArray.push(rvm);
//build chart data
var values = []; //, series = Math.floor(Math.random() * 6) + 6;
for (var i = 0; i < zdata.length; i++) {
values[i] = {
data: [
[zdata[i].HoleSequence, zdata[i].TimePlayed]
],
color: zdata[i].Color
};
}
BarChart('#ChartD-Overview' + rvm.Id(), values);
}
and the BarChart function:
function BarChart(id, data) {
$.plot(id, data, {
series: {
bars: {
show: true,
barWidth: 0.6,
align: "center"
}
},
stack: true,
xaxis: {
mode: "categories",
tickLength: 0
}
});
}
The problem is that I can't manage to get something like this https://imageshack.us/i/expGGpOkp, the little line should be zdata[i].TargetTime. I've tried something using stacked bar chart idea but the result was way different... What am I doing wrong? Can anyone help me with a suggestion to start with to get the same bar chart like in the last image?
Here is something like your second picture using another bar dataseries where the start and end of the bars are the same thereby reducing them to lines, you don't need to stack any of the bars just give them the right y-values (fiddle):
$(function () {
var dataBarsRed = {
data: [
[2, 3], ],
label: 'Bars in Red',
color: 'red'
};
var dataBarsGreen = {
data: [
[1, 2],
[3, 1],
[4, 3]
],
label: 'Bars in Green',
color: 'green'
};
var dataLines = {
data: [
[1, 3, 3],
[2, 3.5, 3.5],
[3, 1.5, 1.5],
[4, 2.5, 2.5]
],
label: 'Lines',
color: 'navy',
bars: {
barWidth: 0.5
}
};
var plot = $.plot("#placeholder", [dataBarsRed, dataBarsGreen, dataLines], {
points: {
show: false
},
lines: {
show: false
},
bars: {
show: true,
align: 'center',
barWidth: 0.6
},
grid: {
hoverable: true,
autoHighlight: true
},
xaxis: {
min: 0,
max: 5
},
yaxis: {
min: 0,
max: 5
}
});
});

Static response WORKS! While Asynchronous doesn't work

I'm creating an angular directive for realtime chart displaying here is the code which returns everything including link:function() { } inside directive.
Here is the code for static directive which works perfectly
angular.module('app').directive("flotChartRealtime", [
function() {
return {
restrict: "AE",
link: function(scope, ele) {
var realTimedata,
realTimedata2,
totalPoints,
getSeriesObj,
getRandomData,
getRandomData2,
updateInterval,
plot,
update;
return realTimedata = [],
realTimedata2 = [],
totalPoints = 100,
getSeriesObj = function() {
return [
{
data: getRandomData(),
lines: {
show: true,
lineWidth: 1,
fill: true,
fillColor: {
colors: [
{
opacity: 0
}, {
opacity: 1
}
]
},
steps: false
},
shadowSize: 0
}, {
data: getRandomData2(),
lines: {
lineWidth: 0,
fill: true,
fillColor: {
colors: [
{
opacity: .5
}, {
opacity: 1
}
]
},
steps: false
},
shadowSize: 0
}
];
},
getRandomData = function() {
if (realTimedata.length > 0)
realTimedata = realTimedata.slice(1);
// Do a random walk
//console.log(realTimedata);
while (realTimedata.length < totalPoints) {
var prev = realTimedata.length > 0 ? realTimedata[realTimedata.length - 1] : 50,
y = prev + Math.random() * 10 - 5;
if (y < 0) {
y = 0;
} else if (y > 100) {
y = 100;
}
realTimedata.push(y);
}
// Zip the generated y values with the x values
var res = [];
for (var i = 0; i < realTimedata.length; ++i) {
res.push([i, realTimedata[i]]);
}
return res;
},
getRandomData2 = function() {
if (realTimedata2.length > 0)
realTimedata2 = realTimedata2.slice(1);
// Do a random walk
while (realTimedata2.length < totalPoints) {
var prev = realTimedata2.length > 0 ? realTimedata[realTimedata2.length] : 50,
y = prev - 25;
if (y < 0) {
y = 0;
} else if (y > 100) {
y = 100;
}
realTimedata2.push(y);
}
var res = [];
for (var i = 0; i < realTimedata2.length; ++i) {
res.push([i, realTimedata2[i]]);
}
return res;
},
// Set up the control widget
updateInterval = 500,
plot = $.plot(ele[0], getSeriesObj(), {
yaxis: {
color: '#f3f3f3',
min: 0,
max: 100,
tickFormatter: function(val, axis) {
return "";
}
},
xaxis: {
color: '#f3f3f3',
min: 0,
max: 100,
tickFormatter: function(val, axis) {
return "";
}
},
grid: {
hoverable: true,
clickable: false,
borderWidth: 0,
aboveData: false
},
colors: ['#eee', scope.settings.color.themeprimary],
}),
update = function() {
plot.setData(getSeriesObj()); // getting .data filled here perfectly
plot.draw();
setTimeout(update, updateInterval);
},
update();
}
};
}
]);
My code with HTTP request which doesn't work
getSeriesObj = function () {
return [{
data: getRandomData(function(res) {
console.log(res) // getting array result here from http call but not returning to data:
return res;
}),
lines: {
show: true,
lineWidth: 1,
fill: true,
fillColor: {
colors: [{
opacity: 0
}, {
opacity: 1
}]
},
steps: false
},
shadowSize: 0
}, {
data: getRandomData2(function (res) {
return res;
}),
lines: {
lineWidth: 0,
fill: true,
fillColor: {
colors: [{
opacity: .5
}, {
opacity: 1
}]
},
steps: false
},
shadowSize: 0
}];
},
getRandomData = function (callback) {
var authToken = window.localStorage.getItem('token');
var url = $rootScope.apiPath + 'Elasticsearch/countget?token=' + authToken;
var res = [];
$http.get(url).then(function (result) {
realTimedata = result.data;
if (realTimedata.length > 0)
//result = [10,22,33,11,32,88,77,66,21,90,92,98,99.9,88.8,76,66,56,88];
for (var i = 0; i < realTimedata.length; ++i) {
var y = realTimedata[i] + Math.random() * 10 - 5;
if (y < 0) {
y = 0;
} else if (y > 100) {
y = 100;
}
res.push([i, y]);
}
callback(res);
});
},
Problem:
When i try following code:
update = function () {
//console.log(getSeriesObj());
plot.setData(getSeriesObj()); // .data property gets undefined
plot.draw();
setTimeout(update, updateInterval);
}
function getSeriesObj() return array of object which return data property to undefined what can be the reason?
how can i resolve this?
Note: This is far different from this question.
When do this
data: getRandomData(function(res) {
return res;
});
You assign the rValue of getRandomData to data.
As stated in your post, getRandomData now has no return statement, so return undefined.
The main problem here is that you expect that plot.setData(getSeriesObj()); work synchronously
Steps
get the data to fill plot
set the data to the plot
draw it
update the values again
Now as the http request work async you cannot expect to retrieve a value from getSeriesObj(). You have to think that getSeriesObj work now async so you can only work with callback that will be fired when the resource is ready to be used
so the update method become
update = function () {
var updateTime = +new Date;
getSeriesObj(function(res){ // execute that stuff when ready
plot.setData(res);
plot.draw();
setTimeout(update, Math.max(10, updateInterval - (+new Date - updateTime)) );
});
}
and getSeriesObj
getSeriesObj = function (callback) {
getRandomData(function(res) {
getRandomData2(function(res2){
var data = [{
data: res,
lines: {
show: true,
lineWidth: 1,
fill: true,
fillColor: {
colors: [{
opacity: 0
}, {
opacity: 1
}]
},
steps: false
},
shadowSize: 0
}, {
data: res2,
lines: {
lineWidth: 0,
fill: true,
fillColor: {
colors: [{
opacity: .5
}, {
opacity: 1
}]
},
steps: false
},
shadowSize: 0
}];
callback(data); // now the ressource obj is now ready to be used
});
});
}

Flot Bar Chart design

I've made this bar chart http://imageshack.com/a/img901/7186/cnOfhh.png, and the code for it is:
//compute & mark average color
for (var i = 0; i < zdata.length; i++) {
if (zdata[i].TargetTime == null) zdata[i].TargetTime = 0;
if (zdata[i].TimePlayed == null) zdata[i].TimePlayed = 0;
if (zdata[i].TargetTime >= zdata[i].TimePlayed) {
zdata[i]['Color'] = 'green';
} else {
zdata[i]['Color'] = 'red';
}
}
//localsitelist
var element = {
rt: 'D',
Id: rid,
courselist: clist,
selcourseId: selCid,
selcourse: selCname,
cartlist: wData,
selSiteId: lsid,
selsite: sitename,
dataList: zdata
}; //, carts: _mVM.availableCarts()}; //
//if rid exists, is update, else its new
var found = -1;
for (var k = 0; k < document.pvm.rapArray().length; k++) {
if (document.pvm.rapArray()[k].Id() == rid) {
document.pvm.rapArray()[k].update(element);
//build chart data
var values = []; //, series = Math.floor(Math.random() * 6) + 6;
for (var i = 0; i < zdata.length; i++) {
values[i] = {
data: [
[zdata[i].HoleSequence, zdata[i].TimePlayed]
],
color: zdata[i].Color
};
}
//var data = [{ data: [[0, 1]], color: "red" }, { data: [[1, 2]], color: "yellow" },{ data: [[2, 3]], color: "green" }];
BarChart('#ChartD-Overview' + rid, values);
found = 1;
break;
}
}
if (found == -1) {
var rvm = new panelViewModel(element);
document.pvm.rapArray.push(rvm);
//build chart data
var values = []; //, series = Math.floor(Math.random() * 6) + 6;
for (var i = 0; i < zdata.length; i++) {
values[i] = {
data: [
[zdata[i].HoleSequence, zdata[i].TimePlayed]
],
color: zdata[i].Color
};
}
BarChart('#ChartD-Overview' + rvm.Id(), values);
}
and the BarChart function:
function BarChart(id, data) {
$.plot(id, data, {
series: {
bars: {
show: true,
barWidth: 0.6,
align: "center"
}
},
stack: true,
xaxis: {
mode: "categories",
tickLength: 0
}
});
}
The problem is that I can't manage to get something like this https://imageshack.us/i/expGGpOkp, the little line should be zdata[i].TargetTime. I've tried something using stacked bar chart idea but the result was way different... What am I doing wrong? Can anyone help me with a suggestion to start with to get the same bar chart like in the last image?
Here is something like your second picture using another bar dataseries where the start and end of the bars are the same thereby reducing them to lines, you don't need to stack any of the bars just give them the right y-values (fiddle):
$(function () {
var dataBarsRed = {
data: [
[2, 3], ],
label: 'Bars in Red',
color: 'red'
};
var dataBarsGreen = {
data: [
[1, 2],
[3, 1],
[4, 3]
],
label: 'Bars in Green',
color: 'green'
};
var dataLines = {
data: [
[1, 3, 3],
[2, 3.5, 3.5],
[3, 1.5, 1.5],
[4, 2.5, 2.5]
],
label: 'Lines',
color: 'navy',
bars: {
barWidth: 0.5
}
};
var plot = $.plot("#placeholder", [dataBarsRed, dataBarsGreen, dataLines], {
points: {
show: false
},
lines: {
show: false
},
bars: {
show: true,
align: 'center',
barWidth: 0.6
},
grid: {
hoverable: true,
autoHighlight: true
},
xaxis: {
min: 0,
max: 5
},
yaxis: {
min: 0,
max: 5
}
});
});

Categories