ChartJS line chart x = y not rendering astraight line - chart.js

I need to render some line that has many points (200) and at the beginning x equals y.
But as you can see on this codepen, the line is not straight.
Is there a way to have a smooth rendering ?
Thank you very much
var ctx = document.getElementById("myChart");
function generateFakeData() {
var res = [];
var i = 0;
for (i = 0; i < 200; ++i) {
res.push(i);
}
return res;
}
var myChart = new Chart(ctx, {
type: "line",
data: {
labels: generateFakeData(),
datasets: [
{
label: "# of Votes",
data: generateFakeData(),
radius: 0,
borderColor: "#156FB4"
}
]
},
options: {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true
}
}
]
}
}
});

If you were to change your fake data function to be:
function generateFakeData() {
var res = [];
res[0] = 0;
res[200] = 200;
return res;
}
and add spanGaps: true to the options, the line will be nice and straight, otherwise the way the pixels line up will make it look jagged as it tries to connect each one.
Not sure if this helps with your use case.

Related

Show highest value untop of a bars when dataset is stacked (chartjs)

I have this code:
animation: {
duration: 500,
onComplete: function() {
var ctx = this.chart.ctx;
var chart = this;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
var datasets = this.config.data.datasets;
ctx.font = "15px QuickSand";
datasets.forEach(function (dataset, i) {
switch ( chart.getDatasetMeta(i).type ) {
case "bar":
ctx.fillStyle = "#303030";
chart.getDatasetMeta(i).data.forEach(function (p, j)
{
ctx.fillText(datasets[i].data[j], p._model.x, p._model.y - 10);
});
break;
}
});
}
}
And these datasets:
datasets: [
{
backgroundColor: '#f87979',
data: [6500, 5500]},
{
backgroundColor: '#f8f8ee',
data: [4800, 5600]
}
]
The dataset is set to be stacked using.
scales: {
xAxes: [{
barThickness: 25,
stacked: true,
ticks: {
beginAtZero: true,
padding: 0,
fontSize: 13
}
}],
yAxes: [{
stacked: true,
display: false
}]
},
What the above code does is placing the values over the bars. My problem is that i want to show the highest value from each dataset at above each bar.
And not all the values from each point.
Can you guys help me with this? I have been trying to do this for like a 1 day now.
To clearify instead of this:
Image with all values
I want this:
Image with wanted values
check out this jsfiddle: https://jsfiddle.net/umsbywLg/2/
essentially I calculated the max value and then drew that on top on the stacked bars:
onComplete: function() {
var ctx = this.chart.ctx;
var chart = this;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
var datasets = this.config.data.datasets;
ctx.font = "15px QuickSand";
ctx.fillStyle = "#303030";
datasets.forEach(function (dataset, i) {
var maxValue = 0;
chart.getDatasetMeta(i).data.forEach(function (p, j) {
if(maxValue < datasets[j].data[i]) {
maxValue = datasets[j].data[i];
}
});
ctx.fillText(maxValue, datasets[i]._meta[0].data[i]._view.x, 20);
});
}

chart.js value is two but only one display tooltip

I have web monitoring data and I want to graph with chart js library in javascript.
Multiple data are at the same moment. However, 'tooltip' displays only one piece of data. Why is this?
Please help me :(
I (A) Login-swlee.zabbix.dev selected and time is 06/25 02:23:21
I (B) First page-swlee.zabbix.dev selected and time is 06/25 02:23:21
I (A) and (B) both selected but tooltip is only one.
```
var colors = ["#FEB500", "#5F8CFC", "#ADC803", "#F0605D"]
var list = data.list;
var list2 = data.list2;
var list3 = data.list3;
var datasets = [];
var labels = [];
for (i = 0; i < list3.length; i++) {
var date = new Date(list3[i].clock * 1000).getTime();
if (labels.indexOf(date) < 0) {
labels.push(date);
}
}
labels.sort();
var tbody = document.getElementById('webTable').children[1];
for (var i = 0; i < list.length; i++) {
var item = list[i];
var td_name = [];
for (var j = 0; j < list2.length; j++) {
var item2 = list2[j];
if (item.hosts[0].hostid == item2.hostid && item2.key_.indexOf('web.test.rspcode') > -1) {
var label = item2.name.replace('$1', item2.key_.substring(17, item2.key_.length - 1).split(',')[0]).replace('$2', item2.key_.substring(17, item2.key_.length - 1).split(',')[1]);
//line chart
var dataset = {
data: [],
label: label,
fill: false,
spanGaps: true,
borderColor: colors[i]
};
for (var k = 0; k < list3.length; k++) {
var item3 = list3[k];
if (item2.itemid == item3.itemid) {
var date = new Date(list3[k].clock * 1000).getTime();
dataset.data.push(null);
if (labels.indexOf(date) > -1) {
dataset.data[labels.indexOf(date)] = item3.value;
}
}
}
datasets.push(dataset);
}
}
}
var ctx = document.getElementById("webChart").getContext("2d");
var gData = {
labels: labels,
datasets: datasets
}
var lineChart = new Chart(ctx, {
type: 'line',
data: gData,
options: {
responsive: true,
scales: {
yAxes: [{
ticks: {
stepSize: 200,
suggestedMin: 0,
suggestedMax: 600
}
}],
xAxes: [{
type: 'time',
time: {
unit: 'minute',
round: 'minute',
displayFormats: {
minute: 'h:mm'
}
},
gridLines: {
display: false
}
}]
},
elements: {
line: {
tension: 0,
}
},
animation: false,
hover: {
animationDuration: 0,
},
responsiveAnimationDuration: 0,
legend: {
display: true,
labels: {
fontColor: '#fff'
}
},
tooltips: {
callbacks: {
title: function(tooltipItems, data) {
return new Date(tooltipItems[0].xLabel).format('MM/dd hh:mm:ss');
}
}
}
}
});
You need to set tooltip­'s mode to index
­­­­­­­­
...
tooltips: {
mode: 'index', //<-- set this
callbacks: {
title: function(tooltipItems, data) {
return new Date(tooltipItems[0].xLabel).format('MM/dd hh:mm:ss');
}
}
}
...

Chart JS Fill Between two lines

I am looking for a way to fill between two lines with Chart.js so that it would look like this. I have looked and everything seems to talk about filling between two lines across zero. I also need other lines to fill all the way down like normal. Is this something chart.js can do?
Here is a solution that uses a plugin to fill between two datasets. Supports all line styles and fill shading between multiple lines. To fill between a dataset, use the custom param fillBetweenSet to tell a dataset to fill the area between another dataset.
Fiddle - https://jsfiddle.net/ke5n5LnL/26/
Preview:
Code:
<html>
<div>
<canvas id="demo"></canvas>
</div>
</html>
<script>
var fillBetweenLinesPlugin = {
afterDatasetsDraw: function (chart) {
var ctx = chart.chart.ctx;
var xaxis = chart.scales['x-axis-0'];
var yaxis = chart.scales['y-axis-0'];
var datasets = chart.data.datasets;
ctx.save();
for (var d = 0; d < datasets.length; d++) {
var dataset = datasets[d];
if (dataset.fillBetweenSet == undefined) {
continue;
}
// get meta for both data sets
var meta1 = chart.getDatasetMeta(d);
var meta2 = chart.getDatasetMeta(dataset.fillBetweenSet);
// do not draw fill if one of the datasets is hidden
if (meta1.hidden || meta2.hidden) continue;
// create fill areas in pairs
for (var p = 0; p < meta1.data.length-1;p++) {
// if null skip
if (dataset.data[p] == null || dataset.data[p+1] == null) continue;
ctx.beginPath();
// trace line 1
var curr = meta1.data[p];
var next = meta1.data[p+1];
ctx.moveTo(curr._view.x, curr._view.y);
ctx.lineTo(curr._view.x, curr._view.y);
if (curr._view.steppedLine === true) {
ctx.lineTo(next._view.x, curr._view.y);
ctx.lineTo(next._view.x, next._view.y);
}
else if (next._view.tension === 0) {
ctx.lineTo(next._view.x, next._view.y);
}
else {
ctx.bezierCurveTo(
curr._view.controlPointNextX,
curr._view.controlPointNextY,
next._view.controlPointPreviousX,
next._view.controlPointPreviousY,
next._view.x,
next._view.y
);
}
// connect dataset1 to dataset2
var curr = meta2.data[p+1];
var next = meta2.data[p];
ctx.lineTo(curr._view.x, curr._view.y);
// trace BACKWORDS set2 to complete the box
if (curr._view.steppedLine === true) {
ctx.lineTo(curr._view.x, next._view.y);
ctx.lineTo(next._view.x, next._view.y);
}
else if (next._view.tension === 0) {
ctx.lineTo(next._view.x, next._view.y);
}
else {
// reverse bezier
ctx.bezierCurveTo(
curr._view.controlPointPreviousX,
curr._view.controlPointPreviousY,
next._view.controlPointNextX,
next._view.controlPointNextY,
next._view.x,
next._view.y
);
}
// close the loop and fill with shading
ctx.closePath();
ctx.fillStyle = dataset.fillBetweenColor || "rgba(0,0,0,0.1)";
ctx.fill();
} // end for p loop
}
} // end afterDatasetsDraw
}; // end fillBetweenLinesPlugin
Chart.pluginService.register(fillBetweenLinesPlugin);
var chartData = {
labels: [1, 2, 3, 4, 5,6,7,8],
datasets: [
{
label: "Set 1",
data: [10, 20, null, 40, 30,null,20,40],
borderColor: "#F00",
fill: false,
steppedLine: false,
tension: 0,
fillBetweenSet: 1,
fillBetweenColor: "rgba(255,0,0, 0.2)"
},
{
label: "Set 2",
data: [60, 40, 10, 50, 60,null,50,20],
borderColor: "#00F",
fill: false,
steppedLine: false,
tension: 0.5
},
{
label: "Set 2",
data: [40, 50, 30, 30, 20,null,60,40],
borderColor: "#0D0",
fill: false,
steppedLine: false,
tension: 0,
fillBetweenSet: 1,
fillBetweenColor: "rgba(5,5,255, 0.2)"
}
]
};
var chartOptions = {
responsive: true,
title: {
display: true,
text: 'Demo Fill between lines'
}
};
var chartDemo = new Chart($('#demo').get(0), {
type: 'line',
data: chartData,
options: chartOptions
});
</script>
Setting fill property to +1 of a dataset will set the backgroundColor from this line to the next line in dataset.
datasets: [{
label: 'Systolic Guideline',
data: [],
fill: '+1',
borderColor: '#FFC108',
backgroundColor: 'rgba(255,193,8,0.2)'
},
{
label: 'Diastolic Guideline',
data: [],
fill: true,
borderColor: '#FFC108',
backgroundColor: 'rgba(0,0,0,0)'
}]
On chart.js v2.0 you have this feature now inside. See https://www.chartjs.org/samples/latest/charts/area/line-datasets.html

Can the colors of bars in a bar chart be varied based on their value?

Using chart.js 2, can the colors of the bars in a bar-cart be varied based on their value?
For example, if the scale is 0 - 100, columns with 50% and above could be green, while 0-49% could be red.
As far as I know there is no configuration or callback for each individual point being drawn. The best way I can think of to do this would be to create a function that would modify your chart config/data object. This isn't the most elegant way to deal with the problem, but it would work.
The Fix
Pass your chart config/data object to a function that will add the background color.
Main Point of the example is function AddBackgroundColors(chartConfig)
Example:
function AddBackgroundColors(chartConfig) {
var min = 1; // Min value
var max = 100; // Max value
var datasets;
var dataset;
var value;
var range = (max - min);
var percentage;
var backgroundColor;
// Make sure the data exists
if (chartConfig &&
chartConfig.data &&
chartConfig.data.datasets) {
// Loop through all the datasets
datasets = chartConfig.data.datasets;
for (var i = 0; i < datasets.length; i++) {
// Get the values percentage for the value range
dataset = datasets[i];
value = dataset.data[0];
percentage = value / range * 100;
// Change the background color for this dataset based on its percentage
if (percentage > 100) {
// > 100%
backgroundColor = '#0000ff';
} else if (percentage >= 50) {
// 50% - 100%
backgroundColor = '#00ff00';
} else {
// < 50%
backgroundColor = '#ff0000';
}
dataset.backgroundColor = backgroundColor;
}
}
// Return the chart config object with the new background colors
return chartConfig;
}
var chartConfig = {
type: 'bar',
data: {
labels: ["percentage"],
datasets: [{
label: '100%',
data: [100]
}, {
label: '50%',
data: [50]
}, {
label: '49%',
data: [49]
}, {
label: '5%',
data: [5]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
};
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
chartConfig = AddBackgroundColors(chartConfig);
var myChart = new Chart(ctx, chartConfig);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.2/Chart.bundle.min.js"></script>
<canvas id="canvas" width="400" height="200"></canvas>
In Chart.js 2 it is possible to set multiple colors with an array.
So you can define the backgroundColor as an array of color strings, matching the datasets data.
var myChart = new Chart(ctx, {
datasets: [{
label: 'Votes',
data: [1, 2, 3],
// Make the first bar red, the second one green and the last one blue
backgroundColor: ['#f00', '#0f0', '#00f']
}]
});
You can easily generate an array based on the values in data:
function getColorArray(data, threshold, colorLow, colorHigh) {
var colors = [];
for(var i = 0; i < data.length; i++) {
if(data[i] > threshold) {
colors.push(colorHigh);
} else {
colors.push(colorLow);
}
}
return colors;
}
See this fiddle for a working demo

Styling Bars and Lines with Chart.js

We have been using Chart.js for several months now and like the power it gives us with ease of programming. One of the things we would like to start adding to the charts produced from Chart.js is a little nicer styling of the charts we generate. Most of the charts we are using are bar charts, with a few line charts thrown in.
When I use the term "styling" what I am really talking about is making the bars or lines look a little nicer. Specifically I would like to add a drop shadow behind the bar and line charts, and maybe even a bevel to the bars.
I've looked through many questions, and can't seem to find what I am looking for. I've also done some experimenting myself by modifying the Chart.js file to add a drop shadow and blur to the javascript, but I'm not getting it added in the correct place. I put these changes inside of the Chart.Element.extend draw function:
ctx.shadowColor = '#000';
ctx.shadowBlur = 10;
ctx.shadowOffsetX = 8;
ctx.shadowOffsetY = 8;
I put it right before the ctx.fill() and it almost does what I want. The result is I get a drop shadow that looks pretty good on both the bar and line charts I am drawing, but I also get a drop shadow on the labels for the x and y axes, which does not look good. I'd like to have the drop shadow on just the bars and the lines, not on the labels.
Any help you can provide would be greatly appreciated. I am not experienced with javascript, but have been able to pull off quite a bit of coding I wouldn't otherwise be able to do without the help of everyone on Stack Overflow.
Adding a Drop Shadow for Line Charts
You can extend the line chart type to do this
Preview
Script
Chart.types.Line.extend({
name: "LineAlt",
initialize: function () {
Chart.types.Line.prototype.initialize.apply(this, arguments);
var ctx = this.chart.ctx;
var originalStroke = ctx.stroke;
ctx.stroke = function () {
ctx.save();
ctx.shadowColor = '#000';
ctx.shadowBlur = 10;
ctx.shadowOffsetX = 8;
ctx.shadowOffsetY = 8;
originalStroke.apply(this, arguments)
ctx.restore();
}
}
});
and then
...
var myChart = new Chart(ctx).LineAlt(data, {
datasetFill: false
});
Fiddle - https://jsfiddle.net/7kbz1L4t/
𝚂𝚘𝚕𝚞𝚝𝚒𝚘𝚗 𝚏𝚘𝚛 𝙲𝚑𝚊𝚛𝚝𝙹𝚂 𝟸.𝚡.𝚡
ᴘʀᴇᴠɪᴇᴡ
ꜱᴄʀɪᴘᴛ overriding the draw function
let draw = Chart.controllers.line.prototype.draw;
Chart.controllers.line.prototype.draw = function() {
draw.apply(this, arguments);
let ctx = this.chart.chart.ctx;
let _stroke = ctx.stroke;
ctx.stroke = function() {
ctx.save();
ctx.shadowColor = '#07C';
ctx.shadowBlur = 10;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 4;
_stroke.apply(this, arguments);
ctx.restore();
}
};
let draw = Chart.controllers.line.prototype.draw;
Chart.controllers.line.prototype.draw = function() {
draw.apply(this, arguments);
let ctx = this.chart.chart.ctx;
let _stroke = ctx.stroke;
ctx.stroke = function() {
ctx.save();
ctx.shadowColor = '#07C';
ctx.shadowBlur = 10;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 4;
_stroke.apply(this, arguments);
ctx.restore();
}
};
let ctx = document.querySelector("#canvas").getContext('2d');
let myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
data: [65, 59, 75, 64, 70, 30, 40],
borderColor: '#07C',
pointBackgroundColor: "#FFF",
pointBorderColor: "#07C",
pointHoverBackgroundColor: "#07C",
pointHoverBorderColor: "#FFF",
pointRadius: 4,
pointHoverRadius: 4,
fill: false,
tension: 0.15
}]
},
options: {
responsive: false,
tooltips: {
displayColors: false,
callbacks: {
label: function(e, d) {
return `${e.xLabel} : ${e.yLabel}`
},
title: function() {
return;
}
}
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
max: 90
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="canvas" width="400" height="210" style="background-color: #E4E8F0"></canvas>
This works for new version of Chart JS
We can create a plugin object and register to the chart JS, Plugins are a way for a developer to modify a chart as it is being created, for reference please look at
https://riptutorial.com/chart-js/example/22332/plugins-introduction
Example Plugin to add a shadow to any of the chart
var simpleplugin = {
beforeDraw : function(chartInstance)
{
let _stroke = chartInstance.ctx.stroke;
chartInstance.ctx.stroke = function () {
chartInstance.ctx.save();
chartInstance.ctx.shadowColor = 'gray';
chartInstance.ctx.shadowBlur = 10;
chartInstance.ctx.shadowOffsetX = 2;
chartInstance.ctx.shadowOffsetY = 2;
_stroke.apply(this, arguments)
chartInstance.ctx.restore();
}
let _fill = chartInstance.ctx.fill;
ctx.fill = function () {
chartInstance.ctx.save();
chartInstance.ctx.shadowColor = 'gray';
chartInstance.ctx.shadowBlur = 10;
chartInstance.ctx.shadowOffsetX = 2;
chartInstance.ctx.shadowOffsetY = 2;
_fill.apply(this, arguments)
chartInstance.ctx.restore();
}
}
}
$(function()
{
Chart.pluginService.register(simpleplugin);
});