I'm testing with Chart.js and trying to remove the grid. My code:
function grafica(){
var chartData = {
labels: [" ", " ", " "],
datasets: [
{
fillColor: "#79D1CF",
strokeColor: "#79D1CF",//marges
data: [30, 40, 45]
}, {
fillColor: "rgb(210,27,71)",
strokeColor: "rgb(210,27,71)",//marges
data: [56, 55, 40]
}, {
fillColor: "rgba(210,27,71,0)",
strokeColor: "rgba(210,27,71,0)",//marges
data: [0, 0, 0]
}
]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myBar = new Chart(ctx).Bar(chartData, {
showTooltips: false,
onAnimationComplete: function () {
var ctx = this.chart.ctx;
ctx.font = this.scale.font;
ctx.fillStyle = this.scale.textColor;
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
}
});
}
How can I do it? I tried some things like add "ctx.gridLines = false;" and "ctx.ticks = false;" but at the moment anything works.
Edit:
I did some changes following your instructions but I don't know why anything work.
The version I'm using is 2.0.0-alpha
On v3 (Updated docs) is changed to
options: {
scales: {
x: {
grid: {
display: false
}
},
y: {
grid: {
display: false
}
}
},
}
I am now using version 2.0Alpha, same as you.
Updated Documentation Link
Below is an example for a simple bar chart without grid lines.
You need to set the 'gridLines' key on the y and xAxis keys of the options object.
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
var barChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: 'Dataset 1',
backgroundColor: "rgba(151,187,205,0.5)",
data: [100,99,98,97,96,95,94]
}]
};
window.myBar = new Chart(ctx).Bar({
data: barChartData,
options: {
responsive: true,
scales: {
xAxes: [{
gridLines: {
show: true
}
}],
yAxes: [{
gridLines: {
show: false
}
}]
}
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.0-alpha/Chart.min.js"></script>
<div>
<canvas id="canvas"></canvas>
</div>
Try it with:
xAxis: {
gridLineWidth: 0
},
yAxis: {
gridLineWidth: 0,
minorTickInterval: null
}
Add this to the chart data,
Related
I'm using Charts.js library to display a line graph from data which is constantly updated. Is there a way to display only the final point value at all times? I want it to do this to monitor the added values at all times.
javascript code:
var config2 = {
type: 'line',
data: {
labels: 0,
datasets: [{
label: "No selection",
lineTension: 0,
borderColor: "rgba(222, 44, 31)",
pointBackgroundColor: "#fff675",
fill: false,
data: 0,
}
]
},
options: {
responsive: true,
title: {
display: false,
text: 'Chart.js Time Point Data'
},
scales: {
x: {
type: 'time',
display: true,
scaleLabel: {
display: true,
labelString: 'Date'
},
ticks: {
major: {
enabled: true
},
fontStyle: function(context) {
return context.tick && context.tick.major ? 'bold' : undefined;
},
fontColor: function(context) {
return context.tick && context.tick.major ? '#FF0000' : undefined;
}
}
},
y: {
display: true,
scaleLabel: {
display: true,
labelString: 'value'
}
}
}
}
};
Each time, a new value is available, you can simply remove outdated labels and dataset.data values once a certain limit is reached. This can be done using Array.shift(), which removes the first element from an array. Once these array are updated, you need to invoke chart.update().
var maxValues = 4;
setInterval(() => {
chart.data.labels.push(new Date());
chart.data.datasets[0].data.push(Math.floor((Math.random() * 20) + 1));
if (chart.data.labels.length > maxValues) {
chart.data.labels.shift();
chart.data.datasets[0].data.shift();
}
chart.update();
}, 1000);
For displaying the value on the last added data point, you can use the Plugin Core API. It offers different hooks that may be used for executing custom code. In below runnable code snippet, I use the afterDraw hook to draw text directly on the canvas.
var chart = new Chart('chart', {
type: "line",
plugins: [{
afterDraw: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['y-axis-0'];
var iLastValue = chart.data.labels.length - 1;
var lastValue = chart.data.datasets[0].data[iLastValue];
var x = xAxis.getPixelForValue(chart.data.labels[iLastValue]);
var y = yAxis.getPixelForValue(lastValue);
ctx.save();
ctx.textAlign = 'center';
ctx.font = '14px Arial';
ctx.fillStyle = "red";
ctx.fillText('Value: ' + lastValue, x, y - 15);
ctx.restore();
}
}],
responsive: true,
maintainAspectRatio: false,
data: {
labels: [],
datasets: [{
label: "Data",
data: [],
fill: false,
lineTension: 0,
backgroundColor: "white",
borderColor: "red",
}]
},
options: {
layout: {
padding: {
right: 50
}
},
scales: {
xAxes: [{
type: 'time',
ticks: {
source: 'auto'
},
time: {
unit: 'second',
displayFormats: {
second: 'mm:ss'
},
tooltipFormat: 'mm:ss'
},
}],
yAxes: [{
ticks: {
min: 0,
max: 20,
stepSize: 5
}
}]
}
}
});
var maxValues = 4;
setInterval(() => {
chart.data.labels.push(new Date());
chart.data.datasets[0].data.push(Math.floor((Math.random() * 20) + 1));
if (chart.data.labels.length > maxValues) {
chart.data.labels.shift();
chart.data.datasets[0].data.shift();
}
chart.update();
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="chart" height="90"></canvas>
How can I add a vertical line for each point and make the selected data to appear with a 5.5k label like on the below screenshot?
You can draw your own lines directly on to the canvas using the Plugin Core API. It offers different hooks that may be used for executing custom code. In below code snippet, I use the afterDraw hook to draw vertical lines up to the individual points from the dataset.
const data = [65, 0, 80, 81, 56, 85, 40];
new Chart(document.getElementById("myChart"), {
type: 'line',
plugins: [{
afterDraw: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['y-axis-0'];
xAxis.ticks.forEach((value, index) => {
var x = xAxis.getPixelForTick(index);
var yTop = yAxis.getPixelForValue(data[index]);
ctx.save();
ctx.strokeStyle = '#aaaaaa';
ctx.beginPath();
ctx.moveTo(x, yAxis.bottom);
ctx.lineTo(x, yTop);
ctx.stroke();
ctx.restore();
});
}
}],
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
data: data,
fill: false
}]
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
gridLines: {
display: false
}
}],
xAxes: [{
gridLines: {
display: false
}
}]
}
}
});
<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js'></script>
<div style="width: 75%">
<canvas id="myChart" height="90"></canvas>
</div>
Please, I need some help to make some suspense in showing poll final results in my chartjs canvas.
The bars have the same duration speed relative to their value, how to set the duration speed to each bar in the chart?
1st step 4 bars at 36%
2nd step 3 bars at 48%
Final Step 1 bar at 60%
This is my chart
This my chartjs code
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
animation:{
duration : 6000,
},
scales: {
yAxes: [{
gridLines: {
show: false,
display:false,
drawBorder: false,
lineWidth: 0,
drawOnChartArea: false
},
ticks: {
beginAtZero: true,
display: false,
maxTicksLimit: 5,
}
}],
xAxes: [{
gridLines: {
show: false,
lineWidth: 0,
display:false,
drawBorder: false,
drawOnChartArea: false,
},
ticks: {
show: false,
display:false,
}
}]
}
}
});
I don't know if there is a better way to do it, but the simplest thing I could think of is to update the dataset according to our needs.
Initially, we can keep all data elements equal and then gradually change them as we want.
Here is a simple solution that I managed to code link.
var canvas = document.getElementById('myChart');
var dataPoints = [65, 59, 30, 81, 56, 55, 40];
var chartData = [];
chartData.length = dataPoints.length;
chartData.fill(nthSmallest(dataPoints, 1));
var doNotOverwrite = [dataPoints.indexOf(chartData[0])];
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 2,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: chartData,
}
]
};
var myBarChart = Chart.Bar(canvas,{
data:data,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
suggestedMax: Math.max(...dataPoints)
}
}]
}
}
});
var index = 0;
var interval = setInterval(()=> {
index++;
var num = nthSmallest(dataPoints, index);
appendArray(num);
doNotOverwrite.push(dataPoints.indexOf(chartData[0]));
myBarChart.update();
if(index == dataPoints.length) {
clearInterval(interval);
}
}, 1000);
function appendArray(num) {
for(let i = 0; i< chartData.length; i++) {
if(!doNotOverwrite.includes(i)) {
chartData[i] = num;
}
}
}
function nthSmallest(numbers, n) {
numbers = JSON.parse(JSON.stringify(numbers));
var sorted = numbers.sort(function (a, b) {
return b - a;
});
return sorted[sorted.length - n];
}
I wrote it in a hurry, so there might be some issues with the code. (Array with repetitive elements will not work as I am using index).
You will also need to update your options for it to work properly.
I know it is not the prettiest solution, but hey it works. :)
I want to show nothing than 0 for zero values on the x-axis (Jan - May). The code below is for the plot. Any help/suggestion appreciated
$scope.showChart = function (finalLabels, finalDatasets, finalTitle, plotType,dateRange) {
var ctx = document.getElementById("chart").getContext('2d');
var plotConfig = {
type: plotType,
data: {
labels: finalLabels,
datasets: finalDatasets
},
options: {
responsive: true,
maintainAspectRatio: false,
layout: {
padding: {left: 0, right: 0, top: 10, bottom: 0}
},
plugins: {
labels: {
render: 'value',
fontSize: 10,
}
},
legend: {
display: false,
labels: {
fontSize: 10,
boxWidth: 35
}
},
scales: {
xAxes: [{
ticks: { autoSkip: false,fontSize:10
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Testing',
fontSize:10
},
ticks: {
beginAtZero: true,
fontSize:10
}
}]
},
/* title: {
display: true,
text: [finalTitle.toUpperCase(),dateRange],
fontSize:10,
padding:0
}*/
}
};
if ($scope.chart) {
$scope.chart.destroy();
}
$scope.chart = new Chart(ctx, plotConfig);
};
If you are using the DataLabels plugin, here is how you can do a scriptable display option.
In the plugin options you can use a function to dictate whether DataLabels shows a label. So in this case its a simple check if the value is greater than 0.
var ctx = document.getElementById("myChart");
debugger;
var data = {
labels: ["Jan 18", "Feb 18", "Mar18", "Apr 18", "May 18", "Jun 18", "Jul 18"],
datasets: [{
label: "# of Votes",
data: [0, 0, 0, 0, 10, 12, 24]
}]
}
var myChart = new Chart(ctx, {
type: 'bar',
data: data,
legend: {
"display": false
},
plugins: [ChartDataLabels],
options: {
plugins: {
// Change options for ALL labels of THIS CHART
datalabels: {
color: "#36A2EB",
anchor: "end",
display: function(context) {
var index = context.dataIndex;
var value = context.dataset.data[index];
return value > 0; // display labels with a value greater than 0
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#0.5.0/dist/chartjs-plugin-datalabels.min.js"></script>
<canvas id="myChart" width="100" height="100"></canvas>
How about formatting text shown on animation.onComplete?
var ctx = document.getElementById("myChart");
debugger;
var data = {
labels: ["2 May", "9 May", "16 May", "23 May", "30 May", "6 Jun", "13 Jun"],
datasets: [{
data: [0, 0, 56, 50, 88, 60, 45],
backgroundColor: "#EEEEEE"
}]
}
var myChart = new Chart(ctx, {
type: 'bar',
data: data,
legend: {
"display": false
},
options: {
"hover": {
"animationDuration": 0
},
"animation": {
"duration": 1,
"onComplete": function() {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function(dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function(bar, index) {
var data = dataset.data[index];
if (data) {
ctx.fillText(data, bar._model.x, bar._model.y - 5);
}
});
});
}
}
}
});
<!doctype html>
<html>
<head>
<title>example.com/test</title>
</head>
<body>
<canvas id="myChart" width="100" height="100"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.js"></script>
</body>
</html>
I added just a condition in the plugin's render and it worked perfectly.
plugins: {
labels: {
render: function (args) {
if (args.value != 0)
return args.value;
},
fontSize: 10
}
},
I am working on chartjs ( version 2.7.2). I want to create a bar chart having a border radius ( 'barradius' as per the chartjs option).
Something Like this:
I have set value for barradius:4 but it is not working.
HTML:
<canvas id="myChart" width="400" height="200"></canvas>
Javascript:
var canvas = document.getElementById('myChart');
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 2,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [65, 59, 20, 81, 56, 55, 40],
}
]
};
var option = {
title: {
display: false,
},
tooltips: {
intersect: false,
mode: 'nearest',
xPadding: 10,
yPadding: 10,
caretPadding: 10
},
legend: {
display: false
},
responsive: true,
maintainAspectRatio: false,
barRadius: 4,
scales: {
xAxes: [{
display: false,
gridLines: false,
stacked: true
}],
yAxes: [{
display: false,
stacked: true,
gridLines: false
}]
},
layout: {
padding: {
left: 0,
right: 0,
top: 0,
bottom: 0
}
}
};
var myBarChart = Chart.Bar(canvas, {
data: data,
options: option
});
var myBarChart = Chart.Bar(canvas, {
data: data,
options: option
});
Also check from here https://jsfiddle.net/anadi/mag91f8k/1006/
As far as i saw in similar problems the solution should be to extend the Chart.types.Bar.extend
https://jsfiddle.net/hyacinthe/t8khnL4q/
Chart.types.Bar.extend({
name: "BarAlt",
initialize: function (data) {
Chart.types.Bar.prototype.initialize.apply(this, arguments);
if (this.options.curvature !== undefined && this.options.curvature <= 1) {
var rectangleDraw = this.datasets[0].bars[0].draw;
var self = this;
var radius = this.datasets[0].bars[0].width * this.options.curvature * 0.2;
// override the rectangle draw with ours
this.datasets.forEach(function (dataset) {
dataset.bars.forEach(function (bar) {
bar.draw = function () {
// draw the original bar a little down (so that our curve brings it to its original position)
var y = bar.y;
// the min is required so animation does not start from below the axes
bar.y = Math.min(bar.y + radius, self.scale.endPoint - 1);
// adjust the bar radius depending on how much of a curve we can draw
var barRadius = (bar.y - y);
rectangleDraw.apply(bar, arguments);
// draw a rounded rectangle on top
Chart.helpers.drawRoundedRectangle(self.chart.ctx, bar.x - bar.width / 2, bar.y - barRadius + 1, bar.width, bar.height, barRadius);
ctx.fill();
// restore the y value
bar.y = y;
}
})
})
}
}
});
The credit of this answer goes to #potatopeelings.