Char.js Interpolation linear - javascript

i'm trying to draw functions with Chart.js
I have a problem with my draw let's see :
here
This is the 'x' function and the line isn't straight
I don't know if it's a problem of resolution or of interpolation
So here is my chart :
var scatterChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
borderWidth:2,
pointRadius :0,
borderColor: 'rgba(0, 0, 255, 1)',
label: 'Scatter Dataset',
data: JSON.parse(data),
fill: false,
lineTension: 0,
cubicInterpolationMode: 'linear'
}]
},
options: {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}]
},
pan: {
enabled: true,
mode: 'xy'
},
zoom: {
enabled: true,
mode: 'xy',
},
responsive: true,
maintainAspectRatio: true,
}
});
Thx guys

The problem is how chart.js is drawing the small line segments between data points. Here is a fiddle that animates a full opacity line over top of a lighter line. The second line is growing at a step=1 while the lighter line is nice and straight [{x:-100,y:-100},{x:100,y:100}]. If you change to step=10 you will see the line fill in straight.
In the code below (or in the fiddle) you can play around with changing the borderWidth, borderColor, and opacity. I tried adding borderCapStyle: 'round' and borderJoinStyle: 'round', but neither seemed to have much effect.
var ctx = document.getElementById("test").getContext("2d");
var i = -100;
var data = [{x: i, y: i}];
var scatterChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
borderWidth: 2,
pointRadius: 0,
borderColor: 'rgba(0, 0, 255, 1)',
label: 'Scatter Dataset 1',
data: data,
fill: false,
lineTension: 0,
cubicInterpolationMode: 'linear'
}, {
borderWidth: 2,
pointRadius: 0,
borderColor: 'rgba(0, 0, 255, 0.4)',
label: 'Scatter Dataset 2',
data: [{x:-100,y:-100},{x:100,y:100}],
fill: false,
lineTension: 0,
cubicInterpolationMode: 'linear'
}]
},
options: {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}]
},
pan: {
enabled: true,
mode: 'xy'
},
zoom: {
enabled: true,
mode: 'xy',
},
responsive: true,
maintainAspectRatio: true,
}
});
var step = 1;
var intervalId = setInterval(function() {
i += step;
if (i <= 100) {
scatterChart.data.datasets[0].data.push({x:i,y:i});
scatterChart.update();
} else {
clearInterval(intervalId);
}
}, 200);
and
<canvas id="test" width="400" height="300"></canvas>

Related

Is it possible to make points in a line chart of Chart JS 3.7.0 look like a donut?

the version of Chart JS is 3.7.0
I am looking for a way to make my chart's points look from this:
to something like this:
I found out that there is an option in this library where you can set the points to a certain shape. e.x: pointStyle: 'rectRot' will make the points appearance look like this:
Is there an option or a way to achieve what Im looking for? (Check the second picture).
Thanks in advance!
My chart's javascript:
const data = {
datasets: [
{
backgroundColor: 'black',
borderColor: '#2d84b4',
borderWidth: 2,
data: [
{ x: 'Dec 27', y: 0.204 },
{ x: '01:00', y: 0.234 },
{ x: '02:00', y: 0.274 },
{ x: '03:00', y: 0.234 },
{ x: '04:00', y: 0.304 },
{ x: 'Dec 28', y: 0.506 },
],
fill: false,
pointBorderColor: 'rgba(0, 0, 0, 0)',
pointBackgroundColor: 'rgba(0, 0, 0, 0)',
pointHoverBackgroundColor: '#2d84b4',
pointHoverBorderColor: '#2d84b4',
},
],
};
const config = {
type: 'line',
data: data,
options: {
animation: {
duration: 0,
},
responsive: true,
maintainAspectRatio: false,
plugins: {
//Do not display legend.
legend: {
display: false,
},
},
scales: {
xAxes: {
stacked: true,
ticks: {
stepSize: 2,
},
grid: {
display: true,
drawBorder: false,
drawOnChartArea: false,
drawTicks: true,
tickLength: 4,
type: 'time',
},
},
yAxes: {
grid: {
drawBorder: false,
drawTicks: false,
},
},
},
elements: {
point: {
radius: 5,
},
},
},
};
// Initialize the Chart.
const myChart = new Chart(document.getElementById('myChart'), config);
window.addEventListener('beforeprint', () => {
myChart.resize(600, 600);
});
window.addEventListener('afterprint', () => {
myChart.resize();
});
//Disable all animations!
myChart.options.animation = false;
myChart.options.animations.colors = false;
myChart.options.animations.x = false;
myChart.options.transitions.active.animation.duration = 0;
The points seemed to work just fine with your transparent background, only on hover you setted a normal background again so the pointHoverBackgroundColor should also be transparent.
To make the point bigger on hover you can use the hoverRadius and to make the line have the same width you can use the pointHoverBorderWidth:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'black',
borderColor: '#2d84b4',
borderWidth: 2,
pointBackgroundColor: 'rgba(0, 0, 0, 0)',
pointHoverBackgroundColor: 'rgba(0, 0, 0, 0)',
pointHoverBorderColor: '#2d84b4',
hoverRadius: 10,
pointHoverBorderWidth: 2
}]
},
options: {}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>

Smaller scale for volume dataset in Chart JS

I'm graphing some stocks data and I wanted to put the volume in a smaller gray bar dataset at the bottom, like in Yahoo Finance.
What I want:
The small grey dataset is at the bottom.
What I get:
Three different Y scales and the size of the volume dataset is the same a the other.
My code:
When I create the chart:
new Chart(context, {
type: 'line',
data: {
labels: timestamps.map(n =>
(new Date(n * 1000)).toLocaleString()
),
datasets: [
dataset,
vdataset
]
},
options: {
maintainAspectRatio: false,
scales: {
xAxis: {
// type: 'time'
ticks: {
//autoSkip: true,
maxTicksLimit: 10
}
},
yAxes: [{
id: 'volume',
display: false
}],
y: {
beginAtZero: false
},
},
animation: {
duration: 0
},
plugins: {
autocolors: false,
annotation: {
annotations
}
},
tooltips: {
mode: 'nearest'
},
hover: {
intersect: false
}
}
});
The volume dataset:
{
type: 'bar',
label: `Volume`,
data: ...,
backgroundColor: 'transparent',
borderColor: 'grey',
fill: 'origin',
pointRadius: 0,
borderWidth: 2,
yAxisID: 'volume'
}
you need to give every dataset a yAxisID and then you should name your axis with that id like this:
Data:
var data = {
labels: labels,
datasets: [{
label: 'My First Dataset',
data: generateTestSeries(),
fill: false,
borderColor: 'rgb(75, 192, 192)',
tension: 0.1,
yAxisID: "something",
},
{
label: 'My Second Dataset',
data: generateTestSeries(),
fill: false,
borderColor: 'rgb(182, 50, 192)',
tension: 0.1,
yAxisID: "volume",
},
]
};
Scales:
scales: {
volume: {
axis: "y",
min: -80,
max: 60,
position: 'right',
},
something: {
axis: "y",
min: -20,
max: 70,
position: 'left',
}
}
Also you shouldn't have the list yAxes, that was how axes were defined in chartjs 2.x
Here is a fiddle to see this in use: JSFiddle
edit: If you want an invisible axis just set display to false as seen in the now updated Fiddle.

when click legend item in chart.js my bar is hiden but value of bar not hide

this is my html code:
<div class="chart col-md-12">
<canvas id="bar-chart-grouped2" style="min-height: 250px; height: 250px; max-height: 400px; max-width: 100%;margin-top:1%;"></canvas>
</div>
and chartjs code
new Chart(document.getElementById("bar-chart-grouped"), {
type: 'bar',
data: {
labels: <%=Newtonsoft.Json.JsonConvert.SerializeObject(Date_Solar_Index)%>,
datasets: [
{
label: "Total_Recived",
backgroundColor: "#17a2b8",
fillColor: "rgba(151,187,205,0.5)",
borderColor: '#e2e2e2',
borderWidth: '2',
data:<%=Newtonsoft.Json.JsonConvert.SerializeObject(POID_MMS_Index)%>,
}, {
label: "valideted",
backgroundColor: "#28a745",
fillColor: "rgba(151,187,205,0.5)",
borderColor: '#e2e2e2',
borderWidth: '2',
data: <%=Newtonsoft.Json.JsonConvert.SerializeObject(COW_POID_MMS_Index)%>,
}, {
label: "Total_rejected",
backgroundColor: "#ff0000",
fillColor: "rgba(151,187,205,0.5)",
borderColor: '#e2e2e2',
borderWidth: '2',
data: <%=Newtonsoft.Json.JsonConvert.SerializeObject(MNP_POID_MMS_Index)%>,
}, {
label: "Total_Back log",
backgroundColor: "#ffc107",
fillColor: "rgba(151,187,205,0.5)",
borderColor: '#e2e2e2',
borderWidth: '2',
data: <%=Newtonsoft.Json.JsonConvert.SerializeObject(Supervisions_Index)%>,
}, {
label: "Total_Back log",
backgroundColor: "#B60A3B",
fillColor: "rgba(151,187,205,0.5)",
borderColor: '#e2e2e2',
borderWidth: '2',
data: <%=Newtonsoft.Json.JsonConvert.SerializeObject(INDEXED_Index)%>,
}, {
label: "Total_Back log",
backgroundColor: "#72098E",
fillColor: "rgba(151,187,205,0.5)",
borderColor: '#e2e2e2',
borderWidth: '2',
data: <%=Newtonsoft.Json.JsonConvert.SerializeObject(Reject_Index)%>,
}
]
},
options: {
maintainAspectRatio: false,
responsive: true,
title: {
display: true,
text: ''
},
legend: { display: true, position: "bottom", onClick: null },
hover: {
animationDuration: 0
},
animation: {
onComplete: function () {
var chartInstance = this.chart;
var ctx = chartInstance.ctx;
ctx.response = true;
ctx.textAlign = "center";
ctx.font = "bold Arial";
//ctx.fillStyle = "black";
Chart.helpers.each(this.data.datasets.forEach(function (dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
Chart.helpers.each(meta.data.forEach(function (bar, index) {
ctx.save();
// Translate 0,0 to the point you want the text
ctx.translate(bar._model.x, bar._model.y - 20);
// Rotate context by -90 degrees
ctx.rotate(-0.5 * Math.PI);
// Draw text
ctx.fillText(dataset.data[index], 0, 0);
ctx.restore();
}), this)
}), this);
}
},
scales: {
xAxes: [{
gridLines: {
display: false
}
}],
yAxes: [{
gridLines: {
color: "rgba(0, 0, 0, 0)",
},
id: 'B',
type: 'linear',
display: false,
position: 'left',
}, {
gridLines: {
color: "rgba(0, 0, 0, 0)",
},
id: 'A',
type: 'linear',
position: 'right',
display: false,
ticks: {
max: 101,
min: 0
}
}]
}
}
});
enter image description here
you have overriden the default onClick method for the legend legend: { display: true, position: "bottom", onClick: null } remove the onClick: null and try again. It should work then
EDIT: Dear, in your afterDraw you never check if the dataset is hidden you always draw te text. And since the data is still in the data object it will just draw it

Chart.js multicolored fill sections

I have a chart which contains blue or green data points depending on the value of a point.
Is it possible to change the fill color beneath these points to reflect their value as well?
Similar to this codepen https://codepen.io/jordanwillis/pen/BWxErp using a gradient of colors switching between them under each data point.
Below is my chart switching between colored datapoints.
var chartColors = {
blue: 'rgb(54, 162, 235)',
green: 'rgb(75, 192, 192)'
}
// x-axis labels
var chartData = {
labels: ['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018', '5/1/2018', '6/1/2018', '7/1/2018'],
datasets: [
{label: 'Light',
fill: true,
borderColor: window.chartColors.blue,
pointBackgroundColor: [],
pointBorderColor: [],
pointRadius: 10,
pointHoverRadius: 10,
data: data1},
]
};
window.onload = function() {
var config = document.getElementById("canvas").getContext("2d");
window.myLine = Chart.Line(config, {
type: "line",
data: chartData,
options: {
responsive: true,
title: {
display: true,
text: ['Light Intensity'],
fontSize: 14
},
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Date (3 day intervals)'
},
type: 'linear',
position: 'bottom',
ticks: {
max: 59,
min: 0,
stepSize: 10,
callback: function(value, index, values) {
return chartData.labels[index];
}
}
}],
yAxes: [{
display: true,
ticks:{min: 0, max: 400, reverse: false},
scaleLabel: {
display: true,
labelString: 'Photosynthetically Available Radiation'
}
}]
}
}
});
};
// change colors of points here
function algeaFill(respiration, depth){
var dataPoints = [];
lightAvgs = [65.3, 33.14, 22.01, 34.74, 26.58, 38.49, 48.12, 44.3, 28.55, 28.92, 37.21, 38.13, 42.49, 44.65, 80.62, 104.66, 87.16, 72.72, 91.07, 93.89, 113.01, 109.56, 110.08, 126.43, 128.98,
165.52, 196.73, 156.93, 140.41, 130.24, 164.14, 150.28, 127.09, 134.54, 129.89, 115.30, 181.71, 259.52, 269.57, 241.86, 221.29, 212.84, 246, 271.05, 238.03, 250.05, 256.02, 236.56, 259.93,
286.6, 283.94, 298.4, 279.81, 256.37, 262.98, 236.18, 305.79, 318.73, 289.67, 277.52];
for(var i = 0; i < 60; i++){
if(lightAvgs[i] <= depth){
window.myLine.data.datasets[0].pointBackgroundColor[i] = "green";
}else{
window.myLine.data.datasets[0].pointBackgroundColor[i] = "blue";
}
dataPoints.push({x: i, y: lightAvgs[i]});
}
return dataPoints;
}
// call algeaFill
window.myLine.data.datasets[0].data = algeaFill(respirationSlider.value, depthSlider.value);
window.myLine.update();
});
in each dataset object insert backgroundColor and pointBackgroundColor properties.
backgroundColor: 'rgb(54, 162, 235)',
pointBackgroundColor: 'rgb(54, 162, 235)'

Why are the default Chart.js legend boxes transparent rectangles?

Why are the default Chart.js legend boxes transparent rectangles like these:
How do I make them solid squares like these instead? I've looked through http://www.chartjs.org/docs/latest/configuration/legend.html but can't find anything relevant.
https://jsfiddle.net/askhflajsf/7yped1d5/ (uses the latest master branch build)
var barChartData = {
labels: ["2013-03-09", "2013-03-16", "2013-03-23", "2013-03-30", "2013-04-06"],
datasets: [{
borderColor: "#3e95cd",
data: [10943, 29649, 6444, 2330, 36694],
fill: false,
borderWidth: 2
},
{
borderColor: "#ff3300",
data: [9283, 1251, 6416, 2374, 9182],
fill: false,
borderWidth: 2
}]
};
Chart.defaults.global.defaultFontFamily = "'Comic Sans MS'";
// Disable pointers
Chart.defaults.global.elements.point.radius = 0;
Chart.defaults.global.elements.point.hoverRadius = 0;
var ctx = document.getElementById("bar-chart").getContext("2d");
new Chart(ctx, {
type: 'line',
data: barChartData,
options: {
responsive: true,
legend: {
display: true,
position: "right"
},
title: {
display: false
},
scales: {
xAxes: [{
type: "time",
ticks: {
minRotation: 90
}
}]
}
}
});
<script src="http://www.chartjs.org/dist/master/Chart.bundle.min.js"></script>
<canvas id="bar-chart"></canvas>
This is because you haven't set the backgroundColor property for your datasets (which is responsible for the legend­'s fill color).
datasets: [{
backgroundColor: "#3e95cd",
borderColor: "#3e95cd",
data: [10943, 29649, 6444, 2330, 36694],
fill: false,
borderWidth: 2
}, {
backgroundColor: "#ff3300",
borderColor: "#ff3300",
data: [9283, 1251, 6416, 2374, 9182],
fill: false,
borderWidth: 2
}]
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
var barChartData = {
labels: ["2013-03-09", "2013-03-16", "2013-03-23", "2013-03-30", "2013-04-06"],
datasets: [{
backgroundColor: "#3e95cd",
borderColor: "#3e95cd",
data: [10943, 29649, 6444, 2330, 36694],
fill: false,
borderWidth: 2
}, {
backgroundColor: "#ff3300",
borderColor: "#ff3300",
data: [9283, 1251, 6416, 2374, 9182],
fill: false,
borderWidth: 2
}]
};
Chart.defaults.global.defaultFontFamily = "'Comic Sans MS'";
// Disable pointers
Chart.defaults.global.elements.point.radius = 0;
Chart.defaults.global.elements.point.hoverRadius = 0;
var ctx = document.getElementById("bar-chart").getContext("2d");
new Chart(ctx, {
type: 'line',
data: barChartData,
options: {
responsive: true,
legend: {
display: true,
position: "right"
},
title: {
display: false
},
scales: {
xAxes: [{
type: "time",
ticks: {
minRotation: 90
}
}]
}
}
});
<script src="http://www.chartjs.org/dist/master/Chart.bundle.min.js"></script>
<canvas id="bar-chart"></canvas>

Categories

Resources