Nest function not summarising values - javascript

I want get sum values for my column "Country", i write this code, but i don't see summarize values
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
</head>
<body>
<canvas id="barchart" width="100%" height="40%"></canvas>
<canvas id="piechart" width="100%" height="40%"></canvas>
<script>
d3.csv("brokenstone copy.csv", function(csv_data) {
var nested_data = d3.nest()
.key(function(d) {return d.Country})
.rollup(function(s){
return d3.sum(s,function(d) {
return d.Amount;
})
})
.entries([csv_data]);
console.log(nested_data);
return csv_data;
}).then(makechart);
function colorGen() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
const transparent = '0.6';
return "rgb(" + r + "," + g + "," + b + "," + transparent + ")";
}
function makechart(csv_data){
// console.log(csv_data);
var prd = [],
amt = [],
frac = [];
csv_data.forEach(element => {
prd.push(element.Country);
amt.push(element.Amount);
});
var alldata = {};
alldata['datasets'] = [];
alldata['labels'] = ['Amount, тн'];
csv_data.forEach(element => {
var sample = {};
sample['data'] = [element.Amount];
sample['backgroundColor'] = colorGen();
sample['label'] = element.Country;
alldata['datasets'].push(sample);
});
var barchart = new Chart('barchart', {
type: 'bar',
data: alldata,
options: {
responsive: true,
legend: {
position: 'top',
},
title: {
display: true,
fontSize: 16,
text: 'Country by amount, тн'
}
}
});
</script>
</body>
</html>
My data:
Year,Month,Country,Amount
2019,2,Germany,70
2019,3,Germany,65
2019,1,Germany,61
2019,1,Germany,39
2019,1,Italy,11966
2019,5,Italy,2489
2019,1,Italy,2262
2019,6,Germany,139
2019,4,Germany,111
2019,5,Germany,69
2019,6,Germany,67

The problem here is quite simple: all your nested_data nest is inside the row function.
The row function is called for each row in your CSV. As the API says,
If a row conversion function is specified, the specified function is invoked for each row, being passed an object representing the current row (d), the index (i) starting at zero for the first non-header row, and the array of column names.
However, that simply won't work for the nest. The nest() method needs to get all the data array.
That being said, just move the nest to inside the then. As you can see, your nest itself has no issues:
const csv = `Year,Month,Country,Amount
2019,2,Germany,70 2019,3,Germany,65
2019,1,Germany,61
2019,1,Germany,39
2019,1,Italy,11966
2019,5,Italy,2489
2019,1,Italy,2262
2019,6,Germany,139
2019,4,Germany,111
2019,5,Germany,69
2019,6,Germany,67`;
const data = d3.csvParse(csv, d3.autoType);
const nested_data = d3.nest()
.key(function(d) {
return d.Country
})
.rollup(function(s) {
return d3.sum(s, function(d) {
return d.Amount;
})
})
.entries(data);
console.log(nested_data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

Related

plotly js globals not being available to other function

This is usually a simple problem to solve with a global var. But nooooo...
All the code works, the csv is read in, the arrays created with the correct values (x,y), a default graph is drawn, but the newPlot function vars are not acting like globals and are empty, so the plot is an empty default of 6x6 with no traces. The newPlot vars are globals. Is plotly.js different? Line 63 is the culprit. This code is pretty much a clone of: plotlyHover
<!DOCTYPE html>
<html lang="en" >
<head>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<div id="myDiv"></div>
<div id="hoverinfo" style="margin-left:80px;"></div>
<!-- cloudcover.csv looks like this.
Time,CloudCover
2022-04-06 10:07:09,0
2022-04-06 11:07:18,100.0
2022-04-06 12:08:17,100.0
2022-04-06 13:09:16,96.0
2022-04-06 14:10:15,66.0
2022-04-06 15:11:14,7.0
-->
<script>
var traces = [];
var layout = {};
var config = {};
const CSV = "cloudcover.csv";
Plotly.d3.csv(CSV, function(rows) {
let x = [];
let y = [];
let row;
let i = 0;
while (i < rows.length) {
row = rows[i];
x.push(row["Time"]);
y.push(row["CloudCover"]);
i += 1;
};
traces = [{
x: x,
y: y,
line: {
color: "#387fba"
},
width: 16,
}];
layout = {
title: 'Cloudcover',
yaxis: {
range: [0, 100]
},
xaxis: {
tickformat: "%H:%M:%S"
}
};
config = {
responsive: true
};
});
Plotly.newPlot('myDiv', traces, layout, config, {
showSendToCloud: true
});
var myPlot = document.getElementById('myDiv')
hoverInfo = document.getElementById('hoverinfo')
myPlot.on('plotly_hover', function(data) {
var infotext = data.points.map(function(d) {
return (d.data.name + ': x= ' + d.x + ', y= ' + d.y.toPrecision(3));
});
hoverInfo.innerHTML = infotext.join('<br/>');
})
myPlot.on('plotly_unhover', function(data) {
hoverInfo.innerHTML = '';
});
</script>
</body>
</html>

optimize data loading in search with Select2

I have a function to display the data in the search box, I used Select2, the function is fine, but it is slow when I want to see the data in the search box, even if I want to click on a data.
For your information, I use Select2 with a big table (> 20 000 entries).
How to fix this problem to avoid the time of data display?
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.full.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/i18n/fr.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://cdn.rawgit.com/eligrey/FileSaver.js/e9d941381475b5df8b7d7691013401e171014e89/FileSaver.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/spin.js/2.0.1/spin.min.js'></script>
.
.
function loadJson(error,values, select2Data){
root = values;
var select2_data = select2Data; // select2Data contains 22500 lines
root.x0 = height / 6;
root.y0 = 0;
_callerNode=root;
root.children.forEach(collapse);
tracePathAndNode(root);
var query = {}
$("#search").select2({
templateResult: function (item) {
var term = query.term || '';
if ( term=='') return item.text;
if (item.loading) {
return item.text;
}
return markMatch(item.text, term);
}
, language: "fr"
, language: {
searching: function (params) {
// Intercept the query as it is happening
query = params;
return 'Searching…';
}
}
,placeholder: "Zone de recherche"
,data: select2_data
,width: '100%'
});
}
function markMatch (text, term) {
// Find where the match is
var match = text.toUpperCase().indexOf(term.toUpperCase());
var $result = $('<span></span>');
// If there is no match, move on
if (match < 0) {
return $result.text(text);
}
// Put in whatever text is before the match
$result.text(text.substring(0, match));
// Mark the match
var $match = $('<span class="select2-rendered__match"></span>');
$match.text(text.substring(match, match + term.length));
// Append the matching text
$result.append($match);
// Put in whatever is after the match
$result.append(text.substring(match + term.length));
return $result;
}
.
.
function searchTree(obj,search,path){
var newSearch = search.replace(/ *\[ Resp:[^)]*\] */g, "");
var newSearch1 = search.replace(/ *\( [^)]*\) */g, "");
if(obj.desc === newSearch && newSearch1){
path.push(obj);
return path;
}
else if(obj.children || obj._children){
var children = (obj.children) ? obj.children : obj._children;
for(var i=0;i<children.length;i++){
path.push(obj);
var found = searchTree(children[i],newSearch && newSearch1,path);
if(found){
return found;
}
else{ path.pop();}
}
}
else{ return false;}
}
var allRhJson;
var select2_data_all;
var currentTypeSelection='ALL';
// loader settings
var opts = {
lines: 9, // The number of lines to draw
length: 9, // The length of each line
width: 5, // The line thickness
radius: 14, // The radius of the inner circle
color: '#EE3124', // #rgb or #rrggbb or array of colors
speed: 1.9, // Rounds per second
trail: 40, // Afterglow percentage
className: 'spinner', // The CSS class to assign to the spinner
};
var target = document.getElementById("tree-container");
var spinner = new Spinner(opts).spin(target);
d3.json("getJson.jsp?dataType=rh", function(data) {
spinner.stop();
allRhJson=data;
select2_data_all = extract_select2_data(allRhJson,[],0)[1];
loadJson(null,allRhJson, select2_data_all ) ;
});
$("#search").on("select2:select", function(e) {
var data = e.params.data.text;
var paths = searchTree(root,data,[]);
if(typeof(paths) !== "undefined"){
openPaths(paths);
}
else{
alert(data+" auncun résultat!");
}
})
d3.select(self.frameElement).style("height", "800px");

Using Chart.Js to plot a scatter plot from an Array

I have written the following code:
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<meta name = viewport" content ="width=device-width, intial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content = "ie=edge">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<link rel ="stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<title>My Chart.js</title>
</head>
<body>
<div class = "container">
<canvas id="myChart"></canvas>
</div>
<script>
var c = [];
var randomNumber = Math.random()*190;
function getRandomDataPoint(x){
if (x == "x"){
var _return
return Math.random()*20;
}
else if (x == "y"){
return Math.random()*10 + randomNumber;
}
else{
}
}
var xPoints = [];
var yPoints = [];
var storage = [];
for(var i=0;i<100;i++)
{
xPoints[i] = Math.random()*20;
yPoints[i] = Math.random()*10 + randomNumber;
x = xPoints[i];
y = yPoints[i];
var json = {x: x, y: y};
storage.push(json);
}
var concatenatedArray = xPoints.concat(yPoints);
let myChart = document.getElementById('myChart');//.getContext('2d');
Chart.defaults.global.defaultColor = '#000000';
let massPopChart = new Chart(myChart, {
type: 'scatter',
data: {
datasets: [{label: 'Data Set', data: [storage]}],
},
options: {
scales: {
yAxes: [{
ticks: {
max: 200,
min: 0,
beginAtZero:true
},
}]
}
}
});
</script>
</body>
</html>
What I would like for this code to do is take 100 random data points and plot them using the for-loop depicted in the code. The issue is the current set of code does create the axis however no data appears to be plotted.
Thank you for any help.
Best Regards
The problem is in how you pass your data values to Chart.js on this line:
datasets: [{label: 'Data Set', data: [storage]}],
Specifically, data is supposed to be an array of objects. Because you have added the square brackets ([]) you are passing an 'array of array of objects'.
The problem can be fixed simply by removing the brackets:
data: storage

Live update highcharts-gauge from dweet

I would like to have the gauge chart update live dweet data, which is success.
The problem is that every time a new data is pushed to the array humidityData, a new pointer is added in the gauge chart as shown here:
guage chart Though I'd like to have one live-updating-pointer instead.
Could this be done by pop() the prev data?
<script language="JavaScript">
//Array to store sensor data
var humidityData = []
<!--START-->
$(document).ready(function() {
//My Dweet thing's name
var name = 'dweetThingName'
//Humidity chart
var setupSecondChart = function() {
var chart2 = {
type: 'gauge'
};
var title = {...};
var pane = {...};
var yAxis = {...};
var tooltip = {
formatter: function () {
return '<b>' + "Humidity: " + Highcharts.numberFormat(this.y, 2) + "%";
}
};
//Series_Humidity
humiditySeries = [{
name: 'Humidity %',
data: humidityData,
tooltip: {
valueSuffix: '%'
}
}]
//Json_Humidity
var humJson = {};
humJson.chart = chart2;
humJson.title = title;
humJson.tooltip = tooltip;
humJson.xAxis = xAxis;
humJson.yAxis = yAxis;
humJson.legend = legend;
humJson.exporting = exporting;
humJson.series = humiditySeries;
humJson.plotOptions = plotOptions;
console.log("Sereies: : " +humJson)
//Container_Humidity
$('#containerHumidity').highcharts(humJson);
}
var humiditySeries = [] ....
dweetio.get_all_dweets_for(name, function(err, dweets){
for(theDweet in dweets.reverse())
{
var dweet = dweets[theDweet];
//Dweet's variables' names
val2 = dweet.content["Humidity"]
//Add the vals into created arrayDatas
humidityData.push(val2)
console.log("HumidityData: " + humidityData)
}
//Call other charts
setupSecondChart()
});
When you initialize/update your chart make sure that data array contains only one element. The dial is created for every point in this array (to visualize it on the plot).

How to transfer Javascript code correctly?

I have two codes, both generate a line chart. However, the first one doesn't use mysql datasource, it uses random math generated datapoints. But it uses a refresh interval and thus is live.
The second code does in fact use a mysql datasource and displays the data in my database in the line-chart. However it is not live, because it does not it has not refresh-interval function.
I was trying to transfer the refresh-Interval / chart-update code parts of the first code to my second code that is not live but uses a real data source.
Here is my live code, with random datapoints:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js">`
<script type="text/javascript">
window.onload = function () {
var dps = []; // dataPoints
var chart = new CanvasJS.Chart("chartContainer2",{
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dps
}]
});
var xVal = 0;
var yVal = 100;
var updateInterval = 20;
var dataLength = 500; // number of dataPoints visible at any point
var updateChart = function (count) {
count = count || 1;
// count is number of times loop runs to generate random dataPoints.
for (var j = 0; j < count; j++) {
yVal = yVal + Math.round(5 + Math.random() *(-5-5));
dps.push({
x: xVal,
y: yVal
});
xVal++;
};
if (dps.length > dataLength)
{
dps.shift();
}
chart.render();
};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval);
}
</script>
This is my code of the static line chart (not live) but uses real data source:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js">`
</script>
<script type="text/javascript">
$().ready(function () {
$.getJSON("arduino_data.php", function (result) {
var dataPoints = [];
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
}
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dataPoints
}]
});
chart.render();
});
});
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
This is what I have tried so far:
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script>
<script type="text/javascript">
$().ready(function () {
$.getJSON("arduino_data.php", function (result) {
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dataPoints
}]
});
var dataPoints = [];
var updateInterval = 20;
var dataLength = 500; // number of dataPoints visible at any point
var updateChart = function (count) {
count = count || 1;
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
};
}
if (dataPoints.length > dataLength)
{
dataPoints.shift();
}
chart.render();
)};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval);
}
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:100%;">
</div>
</body>
</html>
But it keeps saying
Unexpected token ')' at line 42
chart.render();
)};
I am pretty embarrassed but I can't find the solution due to all the bracelets/parenthesizes. I have tried everything. With ) and without } but nothing seems to deliver.
If this is solved, will the chronological positions of the code be alright?
EDIT: FIRST PROBLEM SOLVED, NEW PROBLEM: JS POSITIONING
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script>
<script type="text/javascript">
$().ready(function () {
$.getJSON("arduino_data.php", function (result) {
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dataPoints
}]
});
var dataPoints = [];
var updateInterval = 20;
var dataLength = 500; // number of dataPoints visible at any point
var updateChart = function (count) {
count = count || 1;
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
};
}
if (dataPoints.length > dataLength)
{
dataPoints.shift();
}
chart.render();
});
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(updateChart, updateInterval);
});
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:100%;">
</div>
</body>
</html>
output:
Can't find variable: updateChart
You used )}; instead of });
also at the end of your JS you used only } instead of });
also call your chart like
setInterval(updateChart, updateInterval);
and make sure your updateInterval is in the right function scope.
Here's how it should approximately look like:
jQuery(function ($) {
function updateChart( result ) { // move it here!!!
$.getJSON("arduino_data.php", function( result ){
var dataPoints = [];
var dataLength = 500; // number of dataPoints visible at any point
var updateInterval = 1000;
var chart = new CanvasJS.Chart("chartContainer",{ // new chart Object
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dataPoints
}]
});
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
}
if (dataPoints.length > dataLength){
dataPoints.shift();
}
chart.render();
});
}
// First read - Start
updateChart();
// Update chart after specified time.
setInterval(updateChart, updateInterval);
});

Categories