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>
Related
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>
I'm using Chart.js 2 (React-chart-js 2) to display a line chart.
Does anyone have any reference to keeping the vertical gridline between each displayed label?
It seems like the vertical gridline only showing on each displayed label.
You can make use of the scriptable options for this, see example that hides every second label, you can adjust it to hide a bigger step if you want.
Example:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
scales: {
x: {
ticks: {
callback: function(val, index) {
return index % 2 === 0 ? this.getLabelForValue(val) : '';
}
}
}
}
}
}
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.0.0/chart.js"></script>
</body>
You can try using following configuration
var config = {
type: 'line',
showDatapoints: true,
legend: { position: 'top' },
data: data,
options: {
responsive: true,
hoverMode: 'index',
stacked: false,
title: {
display: true,
text: 'Chart Title'
},
scales: {
yAxes: [{
type: 'linear', // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: 'left',
id: 'y-axis-1',
},
{
type: 'linear', // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: 'right',
id: 'y-axis-2',
// grid line settings
gridLines: {
drawOnChartArea: true, // only want the grid lines for one axis to show up
},
}],
}
}
};
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>
I am using Chart.js to generate a horizontal stacked bar chart. The chart currently looks like this:
This chart shows the user after how many years they should restorate a specific component of a house. I am trying to change this to in which year the user should do the restoration. Adding the current year to the values results to the following:
This is pretty much what I need if I could set the starting value of the x-axis to the current year. I tried to do this setting the minimum value like this:
options: {
scales: {
xAxes: [{
ticks: {
min: 2017
},
...
Unfortunatly results in not displaying the datasets at all like this:
I tried all combinations with adding the current year and setting the minimum values but nothing results in a useful chart.
In the following you can see my current source code:
var mainChart_ctx = document.getElementById("main_chart").getContext("2d");
var mainChart_config = {
type: 'horizontalBar',
data: {
labels: ['Kellerdecke', 'Fenster', 'Außenwand', 'Erdberührter Boden', 'Dach'],
datasets: [{
label: 'Beginn ab heute',
backgroundColor: 'transparent',
data: [4, 21, 25, 25, 25],
borderColor: '#666',
borderWidth: 1
},
{
label: 'Sanierungsdauer',
backgroundColor: '#ffcc00',
data: [2, 5, 5, 5, 5],
borderColor: '#666',
borderWidth: 1
},
{
label: 'Mittlere Restlebensdauer',
backgroundColor: 'orange',
data: [39, 0, 38, 51, 37],
borderColor: '#666',
borderWidth: 1
},
{
label: 'Maximale Restlebensdauer',
backgroundColor: 'orangered',
data: [20, 0, 0, 0, 0],
borderColor: '#666',
borderWidth: 1
}
]
},
options: {
tooltips: {
enabled: true
},
legend: {
display: false
},
title: {
display: true,
text: 'Sanierungsfahrplan',
fontSize: 24
},
scales: {
xAxes: [{
ticks: {
min: 0 /* Todo: change to current year? */
},
stacked: true,
scaleLabel: {
display: true,
labelString: 'Jahre',
fontSize: 16
}
}],
yAxes: [{
ticks: {
stepSize: 10
},
stacked: false,
scaleLabel: {
display: true,
labelString: 'Bauteil',
fontSize: 16
},
}]
}
}
};
mainChart = new Chart(mainChart_ctx, mainChart_config)
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.min.js"></script>
<canvas id="main_chart"></canvas>
I was able to get a suitable result using a callback like this:
xAxes: [{
ticks: {
min: 0,
callback: function (value, index, values) {
return value + 2017;
}
},
...
]
I found that suggestedMin works well:
options: {
scales: {
xAxes: [{
display: true,
ticks: {
suggestedMin: 2017
}
}]
}
}
I've been trying to find a working example on how to implement a slideshow that wraps n canvas elements. I attempted to create a very simple slideshow with my canvases based on an example that used list-items with varying backgrounds instead of canvases.
Based on this fiddle I changed the list elements to this:
<div id="slider">
<ul>
<li> <canvas id="programming"> </canvas> </li>
<li> <canvas id="design"> </canvas> </li>
</ul>
</div>
And this is my javascript:
var designBarChartData = {
labels: ["HTML5", "CSS", "jQuery", "JavaScript", "ASP.NET"],
datasets: [{
label: 'Dataset 1',
backgroundColor: ["rgba(255,82,0,1)", "rgba(0,100,255,0.9)", "rgba(255,255,255,0.9)", "rgba(231,131,0, 1)", "rgba(0,122,204,0.8)"],
borderColor: ['rgba(255,39,0,1)', 'rgba(0,20,255, 1)', 'rgba(0,0,0, 1)', 'rgba(232, 90,0, 1)', 'rgba(0,70,204, 1)'],
borderWidth: 3,
yAxisID: "y-axis-1",
data: [40, 30, 50, 40, 30]
}]
};
var langBarChartData = {
labels: ["Core Java", "C/C++", "C#", "Relational-Databases", "VB.NET", "Erlang", "JavaScript"],
datasets: [{
label: 'Programming',
backgroundColor: ["rgba(102,61,0,0.9)", "rgba(5,32,74,0.9)", "rgba(176,0,255,0.8)", "rgba(101,0,0,0.8)", "rgba(0,115,255,0.8)", "rgba(146,0,0,0.9)", "rgba(236,211,0,0.8)"],
yAxisID: "y-axis-1",
data: [40, 30, 50, 40, 60, 20, 30]
}]
};
window.onload = function() {
var ctx = document.getElementById("design").getContext("2d");
window.myBar1 = Chart.Bar(ctx, {
data: designBarChartData,
options: {
responsive: true,
hoverMode: 'label',
hoverAnimationDuration: 400,
stacked: false,
title:{
display:true,
text:"Chart.js Bar Chart - Multi Axis"
},
scales: {
yAxes: [{
type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: "left",
id: "y-axis-1",
ticks: {
max: 100,
min: 0
}
}, {
type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: "right",
id: "y-axis-2",
gridLines: {
drawOnChartArea: false
}
}],
}
}
});
};
window.onload = function() {
var ctx = document.getElementById("programming").getContext("2d");
window.myBar1 = Chart.Bar(ctx, {
data: langBarChartData,
options: {
responsive: true,
hoverMode: 'label',
hoverAnimationDuration: 400,
stacked: false,
title:{
display:true,
text:"Chart.js Bar Chart - Multi Axis"
},
scales: {
yAxes: [{
type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: "left",
id: "y-axis-1",
ticks: {
max: 100,
min: 0
}
}, {
type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: "right",
id: "y-axis-2",
gridLines: {
drawOnChartArea: false
}
}],
}
}
});
};
Chart.defaults.global.legend.display = false;
It seems most examples cover slideshows of images, whereas in my case I want to create a slideshow of charts (chartjs - which uses a canvas to draw the chart on).