change axis scale to be round numbers instead of decimal - chart.js - javascript

I'm working with chart.js and I can't seem to be able to change the scale of the Y axis to show whole numbers, in this example I would like to have just round numbers in the scale (1,2,3,4,5) instad of the decimal (0 -0,5 - 1,0 - 1,5 - 2,0 - etc)
I'm using a vertical Bar chart from here: https://www.chartjs.org/docs/latest/samples/bar/vertical.html
and my current setup is this:
var setVirtualBarChart = function (element, viewModel) {
var chArea = element.getContext("2d");
var chartConfig = {
type: 'bar',
data: {
labels: ['Categories'],
datasets: [
{
minBarLength: 2,
label: '0-7 days',
barPercentage: 0.75,
categoryPercentage: 0.75,
data: viewModel.ZeroToSevenDaysUser(),
backgroundColor: window.chartColors.BrightVisibleGreen
},
{
minBarLength: 2,
label: '8-30 days',
barPercentage: 0.75,
categoryPercentage: 0.75,
data: viewModel.SevenToThirtyDaysUser(),
backgroundColor: window.chartColors.Orange
},
{
minBarLength: 2,
label: '30+ test days',
barPercentage: 0.75,
categoryPercentage: 0.75,
data: viewModel.ThirtyPlusDaysUser(),
backgroundColor: window.chartColors.BrightRed
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
xAxes: [
{
stacked: false,
display: true,
scaleLabel: {
display: true,
//labelString: 'Categories',
gridLines: {
offsetGridLines: true
}
}
}
],
yAxes: [
{
stacked: false,
display: true,
scaleLabel: {
display: true,
labelString: 'Number of invoices'
},
ticks: {
precision: 0,
min: 0
}
}
]
}
}
};
VirtualBarChart = new Chart(chArea, chartConfig);
};

You are using v2 syntax while using v3, in v3 all scales are objects and no arrays anymore. For all changes please read the migration guide
Exaple:
const options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow"],
datasets: [{
label: '# of Votes',
data: [1, 2.5, 1.5],
backgroundColor: ["Red", "Blue", "Yellow"]
}]
},
options: {
scales: {
y: {
ticks: {
stepSize: 1
},
}
}
}
}
const 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>

Related

chartjs-plugin-streaming: onRefresh() callback isn't working

Hello I'm new in javascript world; I'm trying to display random numbers in real time with Chart.js and chartjs-plugin-streaming starting from a tutorial code which I started to modify for my scope.
const Chart= require ("chart.js");
const chartStreaming = require('chartjs-plugin-streaming');
const boxWhiteColor = "#2043CE";
const pressure_graph = document.getElementById('pressureGraph').getContext('2d');
Chart.register(chartStreaming);
let pressure_graph_config = {
type: 'line',
data: {
datasets: [{
label: 'Pressure',
data: [],
borderColor: boxWhiteColor,
fill: false
}]
},
options: {
title: {
display: true,
text: 'PRESSURE',
fontColor: boxWhiteColor,
fontSize: 30
},
scales: {
xAxes: [{
gridLines: {
display: true,
drawBorder: true,
color: boxWhiteColor,
lineWidth: 5},
ticks: {
fontColor: boxWhiteColor,
display: false
},
type: 'realtime',
realtime: {
duration: 10000,
refresh: 100, // plot at 10 Hz
delay:200,
pause: false, // chart is not paused
ttl: undefined, // data will be automatically deleted as it disappears off the chart
frameRate: 100, // data points are drawn 100 times every second
onRefresh: chart => {
console.log(trocarP.data.datasets.data);
chart.config.data.datasets.forEach(function(dataset) {
chart.data.dataset[0].data.push({
x: Date.now(),
y: Math.random() //pressure16bits[pressure16bits.length-1]
});
});
}
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: '[mmHg]', fontColor: boxWhiteColor, fontSize: 30, fontStyle: 900,
},
ticks: {
fontColor: boxWhiteColor,
fontSize: 25,
fontStyle: 700,
maxTicksLimit: 5,
min: 0,
max: 40,
},
gridLines: {display: true, drawBorder: true, color: boxWhiteColor, lineWidth: 5},
}]
},
elements: {
point: {radius: 0},
},
legend: { display: false}
}
}
trocarP = new Chart (pressure_graph, pressure_graph_config);
The problem is the graph is being created on a canvas via the .html file, but then it doesn't display anything; trying to debug the code I found out that the console.log() I placed inside the onRefresh callback is not printing anything, so I'm assuming the callback isn't working. Any clue on what's happening?
Screenshot of the graph
Edit: I noticed that also Y axis label has not been displayed. I don't get what's wrong with this code.
You are using v2 syntax while using v3 of the lib this wont work as there are several breaking changes, see migration guide for all of them.
For example, way of defining scales has changed, you need an adapter for dates and more.
working basic v3 example:
var options = {
type: 'line',
data: {
datasets: [{
label: '# of Votes',
data: [],
borderColor: 'pink'
}]
},
options: {
scales: {
x: {
type: 'realtime',
realtime: {
duration: 20000,
refresh: 100,
delay: 200,
onRefresh: chart => {
const now = Date.now();
chart.data.datasets.forEach(dataset => {
dataset.data.push({
x: now,
y: Math.random()
});
});
}
}
}
}
}
}
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.5.1/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-streaming/2.0.0/chartjs-plugin-streaming.js"></script>
</body>

Chartjs fixed range on X axis and custom labels

I'm trying to create a scatter plot with Chartjs.
I want to have few datasets centered around one X value, and three Y values.
When I can't set the custom X labels for my dataset, and also can't set a fixed range for X axes.
This is how I generate the data:
function generateData(n, xCenter, yCenter) {
var data = [];
var spread = 0.2
for (var i = 0; i < n; i++) {
data.push({
x: (Math.random() - 0.5)*spread + xCenter,
y: (Math.random() - 0.5)*spread + yCenter
})
}
return data
}
var scatterChartData = {
datasets: [
{
label: 'My First dataset',
backgroundColor: "#0000FF",
data: generateData(100, 1, 2)
},
{
label: 'My Second dataset',
backgroundColor: "#00FF00",
data: generateData(50, 1, 3)
},
{
label: 'My Second dataset',
backgroundColor: "#00FF00",
data: generateData(50, 1, 4)
},
]
}
Here are the scatter options:
var scatterOptions = {
tooltips: {
enabled: true
},
responsive: true, // Instruct chart js to respond nicely.
maintainAspectRatio: false, // Add to prevent default behaviour of full-width/height
responsive: true,
legend: {
display: false
},
scales: {
xAxes: [{
gridLines: {
display: false,
ticks: {
min: 0,
max: 10,
stepSize: 0.01
}
}
}],
yAxes: [{
gridLines: {
display: true,
ticks: {
stepSize: 0.01,
suggestedMin: 0.5,
suggestedMax: 5
}
}
}]
}
}
And this is the plot:
var myChart = new Chart(ctx, {
showTooltips: false,
type: 'scatter',
data: scatterChartData,
options: scatterOptions
});

how to change the Y-axis values from float number to integer in chartjs?

i want to change Yaxis from real number to integer and here is image, and please help me solve this problem
here is my code
var lineChartData = {
labels: time,
datasets: [{
label: "Số người đăng kí ủng hộ",
borderColor: window.chartColors.red,
pointBackgroundColor: window.chartColors.red,
fill: false,
data: people_isProcessing
}, {
label: "Số người đã ủng hộ",
borderColor: window.chartColors.purple,
pointBackgroundColor: window.chartColors.purple,
fill: false,
data: people_isReceived
}]
};
and here is my option for my chart
window.onload = function() {
var chartEl = document.getElementById("chart");
window.myLine = new Chart(chartEl, {
type: 'line',
data: lineChartData,
options: {
title: {
display: true,
text: 'Kindmate - Chart Static Donate'
},
tooltips: {
enabled: true,
mode: 'index',
position: 'nearest',
custom: customTooltips
}
}
});
});
In your case, you can set stepSize property to 1 for y-axis ticks, to change the y-axis values from float number to integer.
options: {
scales: {
yAxes: [{
ticks: {
stepSize: 1
}
}]
},
...
}
ᴅᴇᴍᴏ
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr'],
datasets: [{
label: '# of votes',
data: [1, 2, 3, 4]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
stepSize: 1
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>
Try this:
window.onload = function() {
var chartEl = document.getElementById("chart");
window.myLine = new Chart(chartEl, {
type: 'line',
data: lineChartData,
options: {
title:{
display:true,
text:'Kindmate - Chart Static Donate'
},
tooltips: {
enabled: true,
mode: 'index',
position: 'nearest',
custom: customTooltips
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
callback: function(value) {if (value % 1 === 0) {return value;}}
}
}]
}
}
});

Chart.js Date and Time Bar Chart Not Rendering - Line Works Though

I'm using Chart.js to create a datetime bar chart showing the number of players in multiple servers depending on the date and time of the last scan. However, for some reason, the bar chart will not render. If I use a line type chart, it renders just fine. Anyone know why the bar chart will not render? I don't have any console errors in developer tools.
Here's the fiddle:
https://jsfiddle.net/j3rmjzpw/2/
HTML:
<canvas id='playerChartLine' width='800' height='400'></canvas>
<canvas id='playerChartBar' width='800' height='400'></canvas>
Javascript / jQuery:
$( document ).ready(function() {
renderChartJS("line", "playerChartLine", [{x: "2017-07-04T01:51:02-06:00", y: 240}, {x: "2017-07-04T10:51:02-06:00", y: 150}], "Total Number of Players Playing", "Date", "Players", "188,4,0", 0); // Number of players
renderChartJS("bar", "playerChartBar", [{x: "2017-07-04T01:51:02-06:00", y: 240}, {x: "2017-07-04T10:51:02-06:00", y: 150}], "Total Number of Players Playing", "Date", "Players", "188,4,0", 0); // Number of players
});
function renderChartJS(chartType, elemId, data, title, xAxisLabel, yAxisLabel, rgbaColorStr, yMax){
var ticksObj = {
suggestedMin: 0,
beginAtZero: true,
stepValue: 50,
}
if(yMax != 0){
ticksObj.max = yMax;
}
if(data.length){
var ctx = document.getElementById(elemId).getContext('2d');
var myChart = new Chart(ctx, {
type: chartType,
data: {
datasets: [{
label: yAxisLabel,
data: data,
borderColor: "rgba(" + rgbaColorStr + ",1)",
backgroundColor: "rgba(" + rgbaColorStr + ",0.5)"
}],
},
options: {
responsive: false,
maintainAspectRatio: true,
scaleBeginAtZero: true,
title:
{
display: true,
text: title
},
scales: {
xAxes: [{
type: "time",
display: true,
scaleLabel: {
display: true,
labelString: xAxisLabel
},
ticks: {
minRotation: 90,
maxRotation: 90,
stepValue: 10,
autoSkip: true,
maxTicksLimit: 50
},
time: {
unit: 'minute',
unitStepSize: 10,
max: data[data.length - 1].x
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: yAxisLabel
},
ticks: ticksObj
}]
}
}
});
}
}
The bottom chart should be the bar chart, but it is not rendering properly.
Anyone know what's happening?
The issue is, bar chart doesn't support the type of data format, that you are providing.
You should rather use the following type of data format ...
renderChartJS("line", "playerChartLine", ["2017-07-04T01:51:02-06:00", "2017-07-04T10:51:02-06:00"], [240, 150], "Total Number of Players Playing", "Date", "Players", "188,4,0", 0); // Number of players
renderChartJS("bar", "playerChartBar", ["2017-07-04T01:51:02-06:00", "2017-07-04T01:59:02-06:00"], [240, 150], "Total Number of Players Playing", "Date", "Players", "188,4,0", 0); // Number of players
here, third argument is for x-axis labels and the forth one is for data
and, here's the working version of your code, with this applied ...
$(document).ready(function() {
renderChartJS("line", "playerChartLine", ["2017-07-04T01:51:02-06:00", "2017-07-04T10:51:02-06:00"], [240, 150], "Total Number of Players Playing", "Date", "Players", "188,4,0", 0); // Number of players
renderChartJS("bar", "playerChartBar", ["2017-07-04T01:51:02-06:00", "2017-07-04T01:59:02-06:00"], [240, 150], "Total Number of Players Playing", "Date", "Players", "188,4,0", 0); // Number of players
});
function renderChartJS(chartType, elemId, labels, data, title, xAxisLabel, yAxisLabel, rgbaColorStr, yMax) {
var ticksObj = {
suggestedMin: 0,
beginAtZero: true,
stepValue: 50,
}
if (yMax != 0) {
ticksObj.max = yMax;
}
if (data.length) {
var ctx = document.getElementById(elemId).getContext('2d');
var myChart = new Chart(ctx, {
type: chartType,
data: {
labels: labels,
datasets: [{
label: yAxisLabel,
data: data,
borderColor: "rgba(" + rgbaColorStr + ",1)",
backgroundColor: "rgba(" + rgbaColorStr + ",0.5)"
}],
},
options: {
responsive: false,
maintainAspectRatio: true,
scaleBeginAtZero: true,
title: {
display: true,
text: title
},
scales: {
xAxes: [{
type: "time",
display: true,
scaleLabel: {
display: true,
labelString: xAxisLabel
},
ticks: {
minRotation: 90,
maxRotation: 90,
stepValue: 10,
autoSkip: true,
maxTicksLimit: 50
},
time: {
unit: 'minute',
unitStepSize: 10,
max: data[data.length - 1].x
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: yAxisLabel
},
ticks: ticksObj
}]
}
}
});
}
}
<script src="https://github.com/chartjs/Chart.js/releases/download/v2.6.0/Chart.bundle.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id='playerChartLine' width='800' height='400'></canvas>
<canvas id='playerChartBar' width='800' height='400'></canvas>

chart.js v2: Align time scale labels with the center of the bars

I am trying to align the generated time scale labels using Chart.js v2.2 with the centre of the bars of a bar chart. I have tried the offsetGridLines option but this seems to have no effect when using Xaxis scale type time.
Here is an example, maybe I have missed something:
<div id="container" style="width: 75%;">
<canvas id="canvas"></canvas>
</div>
<script>
var barChartData = {
labels: ["2015-01-01", "2015-02-01", "2015-03-01", "2015-04-01", "2015-05-01", "2015-07-01"],
datasets: [{
label: 'Dataset 1',
backgroundColor: "rgba(220,220,220,0.5)",
data: [10, 4, 5, 7, 2, 3]
}]
};
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
elements: {
rectangle: {
borderWidth: 2,
borderColor: 'rgb(0, 255, 0)',
borderSkipped: 'bottom'
}
},
responsive: true,
legend: {
position: 'top',
},
title: {
display: true,
text: 'Chart.js Bar Chart'
}
,
scales: {
xAxes: [{
categoryPercentage: .5,
barPercentage: 1,
type: 'time',
scaleLabel: {
display: true,
labelString: 'Year-Month'
},
time: {
min: '2014-12-01' ,
max: '2015-12-01',
unit: 'month',
displayFormats: {
month: "MMM YY"
}
},
gridLines: {
offsetGridLines: false,
drawTicks: true,
display: true
},
stacked: true
}],
yAxes: [{
ticks: {
beginAtZero: true
},
stacked: true
}]
}
}
});
};
</script>
This fiddle may help to place the data label in the center of the bar
https://jsfiddle.net/tea8dhgy/
<div id="container" style="width: 75%;">
<canvas id="canvas"></canvas>
</div>
var barChartData = {
labels: ["2015-01-01", "2015-02-01", "2015-03-01", "2015-04-01", "2015-05-01", "2015-07-01"],
datasets: [{
label: 'Dataset 1',
backgroundColor: "rgba(220,220,220,0.5)",
data: [10, 4, 5, 7, 2, 3]
}]
};
var ctx = document.getElementById("canvas").getContext("2d");
new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
elements: {
rectangle: {
borderWidth: 2,
borderColor: 'rgb(0, 255, 0)',
borderSkipped: 'bottom'
}
},
responsive: true,
legend: {
position: 'top',
},
title: {
display: true,
text: 'Chart.js Bar Chart'
},
scales: {
xAxes: [{
categoryPercentage: .5,
barPercentage: 1,
type: 'time',
scaleLabel: {
display: true,
labelString: 'Year-Month'
},
time: {
// min: '2014-12-01' ,
// max: '2015-12-01',
unit: 'month',
displayFormats: {
month: "MMM YY"
}
},
gridLines: {
offsetGridLines: false,
drawTicks: true,
display: true
},
stacked: true
}],
yAxes: [{
ticks: {
beginAtZero: true
},
stacked: true
}]
},
animation: {
onComplete: function() {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.font = Chart.helpers.fontString(10, "bold", Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'center';
this.data.datasets.forEach(function(dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function(bar, index) {
//var data = dataset.data[index];
var data = dataset.data[index];
console.log(bar);
if (data > 0) {
ctx.fillText(data, bar._model.x, bar._model.base - (bar._model.base - bar._model.y) / 2 - 5);
}
});
});
}
}
}
});
I was able to get a working chart by removing the min and max values set.
Here is the JSFiddle
Was the following image the desired outcome?

Categories