2 or more charts on same page? - javascript

As title says Im looking to put 2 or more charts on the same page, but everytime I put the 2nd, the first chart dissapears. What is the correct method to add 2 or more charts?
<!doctype html>
<html>
<head>
<title>Twin</title>
<script src="https://cdn.jsdelivr.net/npm/moment#2.24.0/min/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/hammerjs#2.0.8"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom#0.7.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-streaming#1.8.0"></script>
</head>
<style>
#myChart1 {
position: relative;
left: 25%;
top: 25%;
}
#myChart2 {
position: relative;
left: 55%;
top: 25%;
}
</style>
<!--Charts-->
<body>
<div style="position: relative; height:100px; width:500px">
<canvas id="myChart1" style="border: 1px solid #ccc"></canvas>
</div>
<div style="position: relative; height:100px; width:500px">
<canvas id="myChart2" style="border: 1px solid #ccc"></canvas>
</div>
</div>
<p>
<!--
<button id="randomizeData">Randomize Data</button>
<button id="addDataset">Add Dataset</button>
<button id="removeDataset">Remove Dataset</button>
<button id="addData">Add Data</button>
<button id="resetZoom">Reset Zoom</button> -->
</p>
</body>
<!--1-->
<script>
var chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
function randomScalingFactor() {
return (Math.random() > 0.5 ? 1.0 : -1.0) * Math.round(Math.random() * 100);
}
function onRefresh(chart) {
chart.config.data.datasets.forEach(function(dataset) {
dataset.data.push({
x: Date.now(),
y: randomScalingFactor()
});
});
}
var color = Chart.helpers.color;
var config = {
type: 'line',
data: {
datasets: [{
label: 'Schwingwert',
backgroundColor: color(chartColors.blue).alpha(0.5).rgbString(),
borderColor: chartColors.blue,
fill: false,
cubicInterpolationMode: 'monotone',
data: []
}]
},
options: {
legend: {
position: 'top'
},
title: {
display: true,
text: 'X Axis Zeitstempel (ms) / Y Axis Schwingungswert (m/sec)',
position: 'top'
},
scales: {
xAxes: [{
type: 'realtime',
scaleLabel:{
display: true,
labelString: 'Zeitstempel (ms)'
},
realtime: {
duration: 20000,
refresh: 1000,
delay: 2000,
onRefresh: onRefresh,
}
}],
yAxes: [{
type: 'linear',
display: true,
scaleLabel: {
display: true,
labelString: 'Amplitude (m/sec)'
}
}]
},
tooltips: {
mode: 'nearest',
intersect: false
},
hover: {
mode: 'nearest',
intersect: false
},
pan: {
enabled: true,
mode: 'x',
rangeMax: {
x: 4000
},
rangeMin: {
x: 0
}
},
zoom: {
enabled: true,
mode: 'x',
rangeMax: {
x: 20000
},
rangeMin: {
x: 1000
}
}
}
};
window.onload = function() {
var ctx1 = document.getElementById('myChart1').getContext('2d');
window.myChart = new Chart(ctx1, config);
};
document.getElementById('randomizeData').addEventListener('click', function() {
config.data.datasets.forEach(function(dataset) {
dataset.data.forEach(function(dataObj) {
dataObj.y = randomScalingFactor();
});
});
window.myChart.update();
});
var colorNames = Object.keys(chartColors);
document.getElementById('addDataset').addEventListener('click', function() {
var colorName = colorNames[config.data.datasets.length % colorNames.length];
var newColor = chartColors[colorName];
var newDataset = {
label: 'Dataset ' + (config.data.datasets.length + 1),
backgroundColor: color(newColor).alpha(0.5).rgbString(),
borderColor: newColor,
fill: false,
lineTension: 0,
data: []
};
config.data.datasets.push(newDataset);
window.myChart.update();
});
document.getElementById('removeDataset').addEventListener('click', function() {
config.data.datasets.pop();
window.myChart.update();
});
document.getElementById('addData').addEventListener('click', function() {
onRefresh(window.myChart);
window.myChart.update();
});
document.getElementById('resetZoom').addEventListener('click', function() {
window.myChart.resetZoom();
});
</script>
<!--2-->
<script>
var chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
function randomScalingFactor() {
return (Math.random() > 0.5 ? 1.0 : -1.0) * Math.round(Math.random() * 100);
}
function onRefresh(chart) {
chart.config.data.datasets.forEach(function(dataset) {
dataset.data.push({
x: Date.now(),
y: randomScalingFactor()
});
});
}
var color = Chart.helpers.color;
var config = {
type: 'line',
data: {
datasets: [{
label: 'Schwingwert',
backgroundColor: color(chartColors.blue).alpha(0.5).rgbString(),
borderColor: chartColors.blue,
fill: false,
cubicInterpolationMode: 'monotone',
data: []
}]
},
options: {
legend: {
position: 'top'
},
title: {
display: true,
text: 'X Axis Zeitstempel (ms) / Y Axis Schwingungswert (m/sec)',
position: 'top'
},
scales: {
xAxes: [{
type: 'realtime',
scaleLabel:{
display: true,
labelString: 'Zeitstempel (ms)'
},
realtime: {
duration: 20000,
refresh: 1000,
delay: 2000,
onRefresh: onRefresh,
}
}],
yAxes: [{
type: 'linear',
display: true,
scaleLabel: {
display: true,
labelString: 'Amplitude (m/sec)'
}
}]
},
tooltips: {
mode: 'nearest',
intersect: false
},
hover: {
mode: 'nearest',
intersect: false
},
pan: {
enabled: true,
mode: 'x',
rangeMax: {
x: 4000
},
rangeMin: {
x: 0
}
},
zoom: {
enabled: true,
mode: 'x',
rangeMax: {
x: 20000
},
rangeMin: {
x: 1000
}
}
}
};
window.onload = function() {
var ctx2 = document.getElementById('myChart2').getContext('2d');
window.myChart = new Chart(ctx2, config);
};
document.getElementById('randomizeData').addEventListener('click', function() {
config.data.datasets.forEach(function(dataset) {
dataset.data.forEach(function(dataObj) {
dataObj.y = randomScalingFactor();
});
});
window.myChart.update();
});
var colorNames = Object.keys(chartColors);
document.getElementById('addDataset').addEventListener('click', function() {
var colorName = colorNames[config.data.datasets.length % colorNames.length];
var newColor = chartColors[colorName];
var newDataset = {
label: 'Dataset ' + (config.data.datasets.length + 1),
backgroundColor: color(newColor).alpha(0.5).rgbString(),
borderColor: newColor,
fill: false,
lineTension: 0,
data: []
};
config.data.datasets.push(newDataset);
window.myChart.update();
});
document.getElementById('removeDataset').addEventListener('click', function() {
config.data.datasets.pop();
window.myChart.update();
});
document.getElementById('addData').addEventListener('click', function() {
onRefresh(window.myChart);
window.myChart.update();
});
document.getElementById('resetZoom').addEventListener('click', function() {
window.myChart.resetZoom();
});
</script>
</body>
</html>
Do any of you have any ideas? possibly I am not on the right track!
I tried with different id attributes, but it doesn't work so far!

Your two JavaScript blocks are almost same( same config, same functions, etc...), I refactor to clarify.
Look for my working example: Chart.js multiple charts in same page
Initialize the charts:
...
function onLoadOverride(chartId, config) {
var ctx1 = document.getElementById(chartId).getContext("2d");
new Chart(ctx1, config);
}
onLoadOverride("myChart1", config);
onLoadOverride("myChart2", config);
...

Related

chartjs add space betwen stacked bar

Hello I have stuck with add space between stacked bar, I mean I need to add space or margin or padding between bar color
this what I'm done with
and what I want is like this
as you can see there's is space between green, red and yellow bar
are possible to add it?
I've trying to add options.layout.padding but still not working
const borderRadius = 8;
const borderRadiusAllCorners = { topLeft: borderRadius, topRight: borderRadius, bottomLeft: borderRadius, bottomRight: borderRadius };
const labels = ['0%', '25%', '50%', '75%', '100%'];
const data = {
labels: labels,
datasets: [
{
label: 'LCP',
data: [
90,80,70
],
borderColor: 'green',
backgroundColor: 'green',
borderWidth: 0,
borderRadius: borderRadiusAllCorners,
borderSkipped: 'false',
},
{
label: 'FID',
data: [
8,15,15
],
borderColor: 'yellow',
backgroundColor: 'yellow',
borderWidth: 0,
borderRadius: borderRadiusAllCorners,
borderSkipped: 'false',
},
{
label: 'CLS',
data: [
2,5,15
],
borderColor: 'red',
backgroundColor: 'red',
borderWidth: 0,
borderRadius: borderRadiusAllCorners,
borderSkipped: 'false',
},
]
};
const ctx = $('#cwv-chart');
const myChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
indexAxis: 'y',
elements: {
bar: {
borderRadius: 6,
borderWidth: 2,
}
},
scales: {
x: {
display: false,
stacked: true,
offset: true,
},
y: {
display: false,
stacked: true
}
},
responsive: true,
plugins: {
legend: {
display: false,
},
title: {
display: false,
}
}
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="cwv-chart" height="150"></canvas>
The options.layout.padding is just adding space around the chart area and not between data elements.
I'm doing something like that with a simple plugin, changing the base of the bar element, at runtime.
EDIT: the plugin has been updated in order to avoid bugs when chart hovering.
See snippet:
const ctx = document.getElementById("myChart");
const plugin = {
id: 'fillGaps',
beforeDatasetDraw(chart, args) {
if (args.index > 0 && chart.isDatasetVisible(args.index)) {
args.meta.data.forEach(function(item, i) {
const {width} = item.getProps(['width'], true);
item.base = item.x - width + 3;
});
}
}
};
const myChart = new Chart(ctx, {
type: 'bar',
plugins: [plugin],
data: {
labels: ['January', 'Fabruary', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'user 1 online',
data: [50, 35, 45, 47, 10, 3, 27],
backgroundColor: 'rgba(40, 139, 170, 1)',
borderWidth: 0,
borderSkipped: false,
},
{
label: 'user 2 online',
data: [50, 35, 45, 47, 10, 3, 27],
backgroundColor: 'orange',
borderWidth: 0,
borderSkipped: false,
}]
},
options: {
indexAxis: 'y',
//animation: false,
elements: {
bar: {
borderRadius: {
topLeft: 12,
topRight: 12,
bottomLeft: 12,
bottomRight: 12
},
}
},
scales: {
y: {
stacked: true,
},
x: {
stacked: true,
}
}
}
});
.myChartDiv {
max-width: 600px;
max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.9.1/dist/chart.min.js"></script>
<html>
<body>
<div class="myChartDiv">
<canvas id="myChart" width="600" height="400"/>
</div>
</body>
</html>

how to only show zero grid axes at center and hide all other gridlines in chart js

I am trying to hide all the grid lines on y axis except the middle line which shows the positive values above x axis and negative below y axis.
I found out that zeroWidthLine option isnt avaiable in version 3 anymore.I am attching the js fiddle link in comment.
You can use scriptable options for the grid color to achieve this:
Chart.register(ChartDataLabels);
chartLabels = ['2018', '2019', '2020', 'TTM']
equityToAssetData = [4.32, -5.37, 4.73, 4.89, 3.6, ];
var equityToAssetDatasets = {
labels: chartLabels,
datasets: [{
type: 'line',
label: 'Equity to Asset ',
data: equityToAssetData,
backgroundColor: 'rgb(97,207,5)',
borderColor: 'rgb(97,207,5)',
borderWidth: 1.8,
lineTension: 0.4,
pointStyle: 'rectRot'
}]
}
var chartStylingSingle = {
animation: {
duration: 500,
},
responsive: true,
layout: {
padding: 20
},
interaction: {
mode: 'index',
intersect: false
},
elements: {
point: {
hoverRadius: 5
}
},
plugins: {
legend: {
display: false,
},
datalabels: {
borderWidth: 0.5,
color: 'green',
anchor: 'start',
align: 'end',
offset: 6,
formatter: (v, ctx) => {
let label = ctx.chart.data.labels[ctx.dataIndex];
if (label != 'TTM') {
label = ' ' + label;
}
return label + '\n ' + v;
},
font: {
size: 11,
weight: 'bold',
}
}
},
scales: {
y: {
display: true,
grid: {
color: (ctx) => (ctx.tick.value === 0 ? 'rgba(0, 0, 0, 0.1)' : 'transparent')
}
},
x: {
display: true,
grid: {
display: false,
}
}
}
}
var ctx = document.getElementById('equityToAsset').getContext('2d');
var myChart = new Chart(ctx, {
data: equityToAssetDatasets,
options: chartStylingSingle
})
<canvas id="equityToAsset"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>

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

Prevent chart.js "jumping"

From question ChartJS: How to set fixed Y axis max and min I'm attempting to limit the y axis values using:
ticks : {
max : 200,
min : -200
}
This is in order to prevent the charing "jumping" on incoming data to match the y-axis values range. If there is an alternative to prevent the data jumping please suggest, I assume setting max and min y values will prevent the chart "jumping" as the range is set to a static, rather than dynamic value.
fiddle: https://jsfiddle.net/adrianfiddleuser/yd4mfubp/10/
HTML:
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<script src="https://github.com/nagix/chartjs-plugin-streaming/releases/download/v1.5.0/chartjs-plugin-streaming.min.js"></script>
</head>
<body>
<div>
<canvas id="myChart"></canvas>
</div>
<p>
<button id="randomizeData">Randomize Data</button>
<button id="addDataset">Add Dataset</button>
<button id="removeDataset">Remove Dataset</button>
<button id="addData">Add Data</button>
<span class="label">pause:</span>
<span><input type="checkbox" id="pause" class="control"></span>
</p>
</body>
javascript:
var chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
function randomScalingFactor() {
return (Math.random() > 0.5 ? 1.0 : -1.0) * Math.round(Math.random() * 100);
}
function onRefresh(chart) {
chart.config.data.datasets.forEach(function(dataset) {
dataset.data.push({
x: Date.now(),
y: randomScalingFactor()
});
});
}
var color = Chart.helpers.color;
var config = {
type: 'line',
data: {
datasets: [{
label: 'Dataset 1 (linear interpolation)',
backgroundColor: color(chartColors.red).alpha(0.5).rgbString(),
borderColor: chartColors.red,
fill: false,
lineTension: 0,
borderDash: [8, 4],
data: []
}, {
label: 'Dataset 2 (cubic interpolation)',
backgroundColor: color(chartColors.blue).alpha(0.5).rgbString(),
borderColor: chartColors.blue,
fill: false,
cubicInterpolationMode: 'monotone',
data: []
}]
},
options: {
title: {
display: true,
text: 'Line chart (hotizontal scroll) sample'
},
scales: {
xAxes: [{
type: 'realtime'
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'value',
ticks : {
max : 200,
min : -200
}
}
}]
},
tooltips: {
mode: 'nearest',
intersect: false
},
hover: {
mode: 'nearest',
intersect: false
},
plugins: {
streaming: {
duration: 20000,
refresh: 1000,
delay: 2000,
onRefresh: onRefresh
}
}
}
};
//window.onload = function() {
var ctx = document.getElementById('myChart').getContext('2d');
window.myChart = new Chart(ctx, config);
//};
document.getElementById('randomizeData').addEventListener('click', function() {
config.data.datasets.forEach(function(dataset) {
dataset.data.forEach(function(dataObj) {
dataObj.y = randomScalingFactor();
});
});
window.myChart.update();
});
var colorNames = Object.keys(chartColors);
document.getElementById('addDataset').addEventListener('click', function() {
var colorName = colorNames[config.data.datasets.length % colorNames.length];
var newColor = chartColors[colorName];
var newDataset = {
label: 'Dataset ' + (config.data.datasets.length + 1),
backgroundColor: color(newColor).alpha(0.5).rgbString(),
borderColor: newColor,
fill: false,
lineTension: 0,
data: []
};
config.data.datasets.push(newDataset);
window.myChart.update();
});
document.getElementById('removeDataset').addEventListener('click', function() {
config.data.datasets.pop();
window.myChart.update();
});
document.getElementById('addData').addEventListener('click', function() {
onRefresh(window.myChart);
window.myChart.update();
})
Setting the max and min y-axis values does not appear to fix the issue. How to prevent the chart from "jumping" on incoming data?
Your attempt with defining ticks.min and ticks.max is fine. The only problem is that you defined ticks at the wrong place. Change it as follows and it will work as expected.
yAxes: [{
scaleLabel: {
display: true,
labelString: 'value',
},
ticks: {
max: 100,
min: -100
}
}]
Please have a look at your amended JSFiddle.

Pause chart.js horizontal scroll

Using below code I'm attempting to pause chart.js horizontal scroll:
config.options.scales.xAxes[0].realtime.pause = this.checked;
But it appears the pause is not being registered, when I click the checkbox "pause" the horizontal scroll continues.
Based on question Pause horizontal scrolling in chart.js for real time data they same fix does not apply here.
Fiddle : https://jsfiddle.net/adrianfiddleuser/yd4mfubp/6/
src:
HTML:
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<script src="https://github.com/nagix/chartjs-plugin-streaming/releases/download/v1.5.0/chartjs-plugin-streaming.min.js"></script>
</head>
<body>
<div>
<canvas id="myChart"></canvas>
</div>
<p>
<button id="randomizeData">Randomize Data</button>
<button id="addDataset">Add Dataset</button>
<button id="removeDataset">Remove Dataset</button>
<button id="addData">Add Data</button>
<span class="label">pause:</span>
<span id="pauseValue" class="value">false</span>
<span><input type="checkbox" id="pause" class="control"></span>
</p>
</body>
javascript :
var chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
function randomScalingFactor() {
return (Math.random() > 0.5 ? 1.0 : -1.0) * Math.round(Math.random() * 100);
}
function onRefresh(chart) {
chart.config.data.datasets.forEach(function(dataset) {
dataset.data.push({
x: Date.now(),
y: randomScalingFactor()
});
});
}
var color = Chart.helpers.color;
var config = {
type: 'line',
data: {
datasets: [{
label: 'Dataset 1 (linear interpolation)',
backgroundColor: color(chartColors.red).alpha(0.5).rgbString(),
borderColor: chartColors.red,
fill: false,
lineTension: 0,
borderDash: [8, 4],
data: []
}, {
label: 'Dataset 2 (cubic interpolation)',
backgroundColor: color(chartColors.blue).alpha(0.5).rgbString(),
borderColor: chartColors.blue,
fill: false,
cubicInterpolationMode: 'monotone',
data: []
}]
},
options: {
title: {
display: true,
text: 'Line chart (hotizontal scroll) sample'
},
scales: {
xAxes: [{
type: 'realtime'
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'value'
}
}]
},
tooltips: {
mode: 'nearest',
intersect: false
},
hover: {
mode: 'nearest',
intersect: false
},
plugins: {
streaming: {
duration: 20000,
refresh: 1000,
delay: 2000,
onRefresh: onRefresh
}
}
}
};
//window.onload = function() {
var ctx = document.getElementById('myChart').getContext('2d');
window.myChart = new Chart(ctx, config);
//};
document.getElementById('randomizeData').addEventListener('click', function() {
config.data.datasets.forEach(function(dataset) {
dataset.data.forEach(function(dataObj) {
dataObj.y = randomScalingFactor();
});
});
window.myChart.update();
});
var colorNames = Object.keys(chartColors);
document.getElementById('addDataset').addEventListener('click', function() {
var colorName = colorNames[config.data.datasets.length % colorNames.length];
var newColor = chartColors[colorName];
var newDataset = {
label: 'Dataset ' + (config.data.datasets.length + 1),
backgroundColor: color(newColor).alpha(0.5).rgbString(),
borderColor: newColor,
fill: false,
lineTension: 0,
data: []
};
config.data.datasets.push(newDataset);
window.myChart.update();
});
document.getElementById('removeDataset').addEventListener('click', function() {
config.data.datasets.pop();
window.myChart.update();
});
document.getElementById('addData').addEventListener('click', function() {
onRefresh(window.myChart);
window.myChart.update();
})
document.getElementById('pause').addEventListener('click', function() {
config.options.scales.xAxes[0].realtime.pause = this.checked;
window.myChart.update({duration: 0});
document.getElementById('pauseValue').innerHTML = this.checked;
window.myChart.update();
})
You need to access the property of the actual chart, instead of updating the config.
Try changing config.options.scales.xAxes[0].realtime.pause = this.checked; to window.myChart.chart.options.plugins.streaming.pause = this.checked; in the pause checkbox's click listener.
document.getElementById('pause').addEventListener('click', function() {
window.myChart.chart.options.plugins.streaming.pause = this.checked;
window.myChart.update({duration: 0});
document.getElementById('pauseValue').innerHTML = this.checked;
window.myChart.update();
})

Categories

Resources