Reputation: 33
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);
}
}
},
});
Upvotes: 1
Views: 1486
Reputation: 8124
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]
.
Upvotes: 1