I want to display separate charts. When the user selects more than 1 SensorData on the page it should display the data of the sensors separately. What I'm now getting is basically a so called "multi chart", which I do not want.
This is the code for drawing the chart based upon the data that gets returned from the Ajax POST call:
var visualisesensor = [];
$(document).ready(function () {
//When the button is clicked it should add the ID's from the Sensors I want to visualise in to an array.
$("#visualisebtn").click(function () {
$.each($("input[name='removecheckbox']:checked"), function () {
visualisesensor.push($(this).val());
});
//This is where I create multiple DIVs based upon howmany Sensors the user selected to display
for (var i = 0; i < visualisesensor.length; i++) {
$("#chart-container").append("<canvas id=" + visualisesensor[i] + "></canvas>");
}
//This is where I basically draw the charts based upon the amount of sensors the user selected
$.ajax({
url: "visualise.php",
method: "POST",
data: {visualisesensor: visualisesensor},
success: function (data) {
var Sensornaam = [];
var Temperatuur = [];
for (var i in data) {
Sensornaam.push("Sensor: " + data[i].Sensornaam);
Temperatuur.push(data[i].Temperatuur);
}
var chartdata = []
for (var k = 0; k < data.length; k++) {
chartdata = {
labels: Temperatuur,
datasets: [
{
label: 'Sensor Temperatuur',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: Temperatuur[k]
}
]
};
}
for (var j = 0; j < data.length; j++) {
var ctx = $("#" + data[j].SensorID);
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
});
console.log(chartdata[j]);
alert('Chart has been added!');
}
},
error: function (data) {
console.log(data);
}
});
});
});
This is the visualise.php code:
<?php
//setting header to json
header('Content-Type: application/json');
include ('../DATABASE/connection.php');
if(isset($_POST["visualisesensor"]))
{
$j = implode(',',$_POST["visualisesensor"]);
$query = sprintf("SELECT SensorID, Sensornaam, Temperatuur FROM sensoren WHERE SensorID in ($j)");
$result = $con->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$con->close();
//now print the data
print json_encode($data);
}
?>
What I'm now getting is a multichart. It display the data that's in the array successfully, but just in the same chart. I want the data of the sensors to be separately displayed. How would I go about this?
What's inside data:
Picture of database:
Picture of the output I get (and don't want):
The success function of the $.ajax call is very odd; I can't understand why the data variable is iterated 3 separate times. Since no test data was provided in the question I've reverse-engineered some, based on the code, and created a simplified answer that draws three separate charts:
// spoofed user input for testing.
var visualisesensor = ['1', '2'];
// spoofed ajax result data for test purposes.
var data = [{
SensorID: '1',
Sensornaam: 'tempsensor',
Temperatuur: '45'
}, {
SensorID: '2',
Sensornaam: 'meter',
Temperatuur: '83'
}];
for (var i = 0; i < visualisesensor.length; i++) {
$("#chart-container").append("<canvas id=" + visualisesensor[i] + "></canvas>");
}
for (var i = 0; i < data.length; i++) {
var ctx = $("#" + data[i].SensorID);
var chartdata = {
labels: [data[i].Sensornaam],
datasets: [{
label: 'Sensor Temperatuur',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: [data[i].Temperatuur]
}]
};
new Chart(ctx, {
type: 'bar',
data: chartdata,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chart-container"></div>
Related
I just learned to make a web And I want to know how to make chart js to display values in real time. Can you guys advise or tell me how to do it for me?
var data = [];
var temp = [];
async function getRandomUser() {
const response = await fetch('http://localhost:1111/chartpie');
const data = await response.json();
addData(data);
}
function addData(object) {
temp.push(object.temperature);
var z = 80;
var y = z - temp;
var ctx = document.getElementById("myPieChart");
myPieChart = new Chart(ctx, {
type: "doughnut",
data: {
labels: ["Temperature", "Null"],
datasets: [{
data: [temp, y],
backgroundColor: [
"orange",
"rgba(0, 172, 105, 1)"
],
}]
},
options: {
legend: {
display: false
},
}
});
}
getRandomUser()
The values I retrieved are the values retrieved from mongoDB, fetched in the form of an array. Thank You!
You can just update the chart in "real time" by adding to the charts data array.
see: https://www.chartjs.org/docs/latest/developers/updates.html
Adding and removing data is supported by changing the data array. To
add data, just add data into the data array as seen in this example.
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
}
For example...
const canvas = document.getElementById('myChart');
canvas.height = 75;
const labels = [
'dju32',
'ad6b2',
'0f23f',
'asd4c',
];
const data = {
labels: labels,
datasets: [{
label: 'Test',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 4],
}]
};
const config = {
type: 'line',
data: data,
options: {}
};
const myChart = new Chart(
canvas,
config
);
// function to update the chart
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
}
// randomly add new data
setInterval(function() {
const newLabel = (Math.random() + 1).toString(36).substring(7);
const newData = Math.floor(Math.random() * (10 - 1 + 1)) + 1;
addData(myChart, newLabel, newData);
}, 1000);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div>
<canvas id="myChart"></canvas>
</div>
I want to pass a parameter to chart line based to json iput s data1 instead of var labeltabmles = ['Redddd', 'Blue', 'Yellow', 'Green'];
var datalabel = [1240, 190, 30, 545];
I did the algorithme below in order to get the values of count on variable listcount and get the values of type on variable listtype to configure parameter labels and data of line chart configuration from json file inputs using the code below :
listcount = [];
listtype = [];
......
ngOnInit(): void {
var data1 = [{
"type": "MATH",
"count": 55
}, {
"type": "ENGLISH",
"count": 22
},
{
"type": "SCINETIST",
"count": 18
}];
for (var key in data1) {
var typeelement = data1[key]["type"];
var countelemtn = data1[key]["count"];
this.listtype.push(typeelement);
this.listcount.push(countelemtn);
console.log(this.listcount);
console.log(this.listtype);
}
console.log(this.listcount);
console.log(this.listtype);
var labeltabmles = ['Redddd', 'Blue', 'Yellow', 'Green'];
var datalabel = [1240, 190, 30, 545];
const myChart1 = new Chart("myChartline", {
type: 'line',
data: {
labels: labeltabmles,
datasets: [{
label: '# of Votes',
data: datalabel,
backgroundColor: "#007ee7",
borderColor: "#007ee7",
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
i want to configure the var labeltabmles = ['Redddd', 'Blue', 'Yellow', 'Green'];
var datalabel = [1240, 190, 30, 545]; using the variables listcount , listtype
where the result of this two array are following the code enter image description here
i need your help to pass listcount and listtype as paramter to datalabel and data of the chart
i tried but the apped didnt happen the this.listype and this.listcount still empty;
var labeltabmles = this.listcount ;
var datalabel = this.listype;
Thanks for your support and help
i find the solution by :
-using the TYPELIST: any = []; COUNTLIST: any = [];
-and update the variable used on push function on the for iteration
for (var key in data1) {
var typeelement = this.contentype[key]["type"];
var countelemtn = this.contentype[key]["count"];
this.TYPELIST.push(typeelement);
this.COUNTLIST.push(countelemtn);
}
const myChart1 = new Chart("myChartline", {
type: 'line',
data: {
labels: this.TYPELIST,
datasets: [{
label: '# of Votes',
data: this.COUNTLIST,
backgroundColor: "#007ee7",
borderColor: "#007ee7",
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
I want to make range of labels like 90 to 1. How I can do it insted of typeing '90',89','88',....
Please help. Should I use ForEach loop or something else or there is some function like range(1-90)?
$.getJSON("/administration/statistics/datasource/grafpobrojuuplata90dana.json", function (data) {
zbrojevi = data.zbrojevi;
var result = Object.values(zbrojevi);
console.log(result);
var ctx = document.getElementById('grafpobrojuuplata90dana').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
axisX:{
scaleBreaks: {
autoCalculate: true
}
},
toolTip: {
shared: true
},
// The data for our dataset
data: {
labels: ['90','89','88','87','86','85','84','83','82','81','80','79','78','77','76','75','74','73','72','71','70','69','68','67','66','65','64','63','62','61','60','59','58','57','56','55','54','53','52','51','50','49','48','47','46','45','44','43','42','41','40','39','38','37','36','35','34','33','32','31','30','29', '28', '27', '26', '25', '24', '23','22','21','20','19','18','17','16','15','14','13','12','11','10','9','8','7','6','5','4','3','2','1','danas'],
datasets: [{
label: 'Graf po broju uplata 90 dana',
backgroundColor: 'rgb(51, 153, 255)',
borderColor: 'rgb(0, 0, 255)',
data: result
}]
},
});
});
var label = [];
for (var j = 90; j >= 1; j--) {
label.push(j);
}
console.log(label);
I'm having next problem -> when i use the encode json string printed by a php echo tag in my front-end everything works, but when i want to use it with the angular get function I don't get it to work.
Codeigniter Controller (back-end)
public function getLogs(){
$this->load->model('Home_model');
$logs = $this->Home_model->getLogs();
echo json_encode($logs);
}
AngularJs Controller (front-end)
$http.get('index.php/Welcome/getLogs')
.then(function (response) {
json = response.data;
});
var chartjsData = [];
for (var i = 0; i < json.length; i++) {
chartjsData.push(json[i].aantal);
}
var chartjsLabels = [];
for (var i = 0; i < json.length; i++) {
chartjsLabels.push(json[i].datum);
}
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: chartjsLabels,
datasets: [{
label: "Aantal meldingen",
borderColor: 'rgb(255, 131, 48)',
data: chartjsData,
fill: false
}]
},
options: {
responsive: false
}
});
Thanks in advance!
Since, the $http.get() method is asynchronous, you need to initialize your chart inside the callback function of $http.get() , like so ...
$http.get('index.php/Welcome/getLogs')
.then(function(response) {
json = response.data;
json = JSON.parse(json); //parse JSON string (if needed)
var chartjsData = [];
for (var i = 0; i < json.length; i++) {
chartjsData.push(json[i].aantal);
}
var chartjsLabels = [];
for (var i = 0; i < json.length; i++) {
chartjsLabels.push(json[i].datum);
}
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: chartjsLabels,
datasets: [{
label: "Aantal meldingen",
borderColor: 'rgb(255, 131, 48)',
data: chartjsData,
fill: false
}]
},
options: {
responsive: false
}
});
});
I am trying to set the backgroundColor and borderColor based on the dynamic data I get, I am also trying to alternate the color if the "score" number is even or odd I can't find a way to get it done. Any suggestions is very appreciated.
<!DOCTYPE html>
<html>
<head>
<title>ChartJS - BarGraph</title>
<style type="text/css">
#chart-container {
width: 800px;
height: 600px;
}
</style>
<!-- javascript -->
<script type="text/javascript" src="jquery-1.11.min.js"></script>
<script type="text/javascript" src="Chart.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
//url: "test.html",
//method: "GET",
success: function(data) {
// test data
var data = [
{
"Serverid":"1",
"score":"37"
},
{
"Serverid":"2",
"score":"60"
},
{
"Serverid":"3",
"score":"35"
},
{
"Serverid":"4",
"score":"41"
},
{
"Serverid":"5",
"score":"50"
},
{
"Serverid":"6",
"score":"70"
}
// ... it can be more than that
];
var Server = [];
var score = [];
for(var i in data) {
Server.push("Server " + data[i].Serverid);
score.push(data[i].score);
}
var chartdata = {
labels: Server,
datasets : [
{
label: 'Score I',
backgroundColor: [
// even color
'rgba(255, 99, 132, 0.2)',
// odd color
'rgba(75, 192, 192, 0.2)'
],
borderColor: [
// even color
'rgba(255,99,132,1)',
// odd color
'rgba(153, 102, 255, 1)'
],
borderWidth: 1,
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: score
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}, // end success
error: function(data) {
console.log(data);
alert(data);
}
}); // end ajax
});
</script>
</head>
<body>
<br> Test Bar 3 <br>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
</body>
</html>
Thank you!
There isn't really anything special that is required to dynamically set your bar background and border colors, it all just depends on what logic you want to use to set the colors.
Per the API, chart.js allows you to pass in an array of colors (instead of just a simple color) in your bar chart dataset for backgroundColor and borderColor. You can control data point colors because the index in this array maps to the index in your data array. In other words, if you want to color the 2nd data point blue, then insert blue into the 2nd index of the color array.
So all you need to do is iterate over your dynamic data and build your data, backgroundColor, and borderColor arrays per your logic (alternating colors). Here is an example.
function getData(data) {
var dataSize = Math.round(Math.random() * 100);
var evenBackgroundColor = 'rgba(255, 99, 132, 0.2)';
var evenBorderColor = 'rgba(255,99,132,1)';
var oddBackgroundColor = 'rgba(75, 192, 192, 0.2)';
var oddBorderColor = 'rgba(153, 102, 255, 1)';
var labels = [];
var scoreData = {
label: 'Mid-Term Exam 1',
data: [],
backgroundColor: [],
borderColor: [],
borderWidth: 1,
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
};
for (var i = 0; i < dataSize; i++) {
scoreData.data.push(window.randomScalingFactor());
labels.push("Score " + (i + 1));
if (i % 2 === 0) {
scoreData.backgroundColor.push(evenBackgroundColor);
scoreData.borderColor.push(evenBorderColor);
} else {
scoreData.backgroundColor.push(oddBackgroundColor);
scoreData.borderColor.push(oddBorderColor);
}
}
return {
labels: labels,
datasets: [scoreData],
};
};
Here is a codepen example demonstrating what I mean.
Now, to map this back to your specific example, you would simply call your getData() method from within your $.ajax success callback (or just copy the essence of my example directly into your callback). Here is an example of what your code (supplied from your question) would look like calling the above getData() function.
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
//url: "test.html",
//method: "GET",
success: function(data) {
var ctx = $("#mycanvas");
// create our chart and pass it the data returned from the ajax request
var barGraph = new Chart(ctx, {
type: 'bar',
// pass the data returned from the ajax request so we can assemble it
data: getData(data),
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}, // end success
error: function(data) {
console.log(data);
alert(data);
}
}); // end ajax
});
</script>
Or just take a look at this other example showing the solution mapped to your code.
public class TheServerController : Controller
{
public ActionResult Index()
{
return View();
}
//Json Function To Call The Data
public JsonResult DummyServerData()
{
List<TheServer> allDummyServers = ServerRepository.GetAllServers();
Chart _chart = new Chart();
//Create And Load Server-Names-Array
_chart.labels = allDummyServers.Select(x => x.ServerId).ToArray();
//Create Scores-Array
int[] scores = allDummyServers.Select(x => x.Score).ToArray();
//Create An Empty-Colors-Array With The Same Size As Scores.Count
string[] colours = new string[scores.Length];
for (int i = 0; i < scores.Length; i++)
{
//Load The Colours-Array With As Per Index(i) Of The Scores-Array
//By Calling The Coloring Function From Repository
colours[i] = ServerRepository.GetColourStringNameBasedOnScore(scores[i]);
}
_chart.datasets = new List<Datasets>();
List<Datasets> _dataSet = new List<Datasets>();
_dataSet.Add(new Datasets()
{
label = "Server Scores",
data = scores,// Adding The Scores To Dataset
backgroundColor = colours,// Adding The Colours To Dataset
borderWidth = "1"
});
_chart.datasets = _dataSet;
return Json(_chart, JsonRequestBehavior.AllowGet);
}
}