Flot not honoring series config for "dynamically" created charts - javascript

The second chart below should have a green line and red dots like the first one, however it didn't happen:
CHART IMAGE HERE: unfortunately i can't post images but the sample is simple enough to be opened in a browser to see it.
Here's my default.html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>My Flot Sample</title>
<link href="Content/examples.css" rel="stylesheet" />
<script src="Scripts/jquery.js"></script>
<script src="Scripts/jquery.flot.js"></script>
</head>
<body>
<input id="Submit1" type="submit" value="submit"/>
<div id="myPlot13" style="width:600px;height:300px"></div>
<div id="myPlot24" style="width:600px;height:300px"></div>
<script src="Scripts/default.js"></script>
</body>
</html>
And here's default.js:
var x = 0;
var y = 0;
var numPoints = 50;
var delay = 50;
var d1 = [];
var d2 = [];
var d3 = [];
var d4 = [];
var serie1 = {
color: "#00FF00",
data: d1,
lines: {
lineWidth: 0.5
}
};
var serie2 = {
color: "#00FF00",
data: d2,
lines: {
lineWidth: 0.5
}
};
var serie3 = {
color: "#FF0000",
data: d3,
points: {
show: true,
lineWidth: 0,
fill: true,
fillColor: "#FF0000",
radius: 7
}
};
var serie4 = {
color: "#FF0000",
data: d4,
points: {
show: true,
lineWidth: 0,
fill: true,
fillColor: "#FF0000",
radius: 7
}
};
var data13 = [serie1, serie3];
var data24 = [serie2, serie4];
var options = {
grid: {
backgroundColor: "#000000",
color: "#FFFFFF"
}
};
function init_data13() {
for (x = 0; x < numPoints; x++) {
y += (Math.random() - 0.5);
d1.push([x, y]);
if (x % 15 == 0 && x > 0) {
d3.push([x, y]);
}
}
}
function getData24() {
if (d2.length < numPoints) {
y += (Math.random() - 0.5);
d2.push([x, y]);
if (x % 15 == 0 && x > 0) {
d4.push([x, y]);
}
x++;
}
return [d2, d4];
}
init_data13();
$.plot("#myPlot13", data13, options);
var btn = document.getElementById('Submit1');
btn.onclick = addChart;
function addChart() {
x = 0;
y = 0;
var somePlot = $.plot("#myPlot24", data24, options);
function updatePlot() {
somePlot.setData(getData24());
somePlot.draw();
somePlot.setupGrid();
setTimeout(updatePlot, delay);
}
updatePlot();
}
The only difference is that the second chart is created "dynamically" when the SUBMIT button is clicked.

Apologies for that, I understand now. See here for a working demo (that updates in real time). I modified the updatePlot() function as follows:
function updatePlot() {
// Destroy the current chart
somePlot.shutdown();
// Get the data with the new data point
getData24();
// Recreate the chart
somePlot = $.plot("#myPlot24", data24, options);
setTimeout(updatePlot, delay);
}
It computes the next point by calling getData24() then calls the $.plot function to recreate the chart with the new data point.
Edit
Have found another way to do it without creating a brand new chart. You can call the getData24() function then pass data24 as a parameter to somePlot.setData()
function updatePlot() {
// Add the next data point
getData24();
// Pass the data to the existing chart (along with series colours)
somePlot.setData(data24);
somePlot.draw();
somePlot.setupGrid();
setTimeout(updatePlot, delay);
}
See here for a Fiddle

Related

Draw line in Phaser 3

I need your help. I am newbie in Phaser 3. I want to create game with simple rules. There are 36 dots, which situated in 6 rows. Player needs to unite dots with a line, but he can only unite dots with same color and union can happen only vertically and horizontally. So, you can't draw daigonal line. When you will finish union, dots will vanish. How I can realize union with line? My current code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/phaser.min.js"></script>
</head>
<body>
<script>
let config = {
type: Phaser.AUTO,
width: 800,
height: 600,
backgroundColor: '#f0ebeb',
physics: {
default: 'arcade',
arcade: {
gravity: { y: 300 },
debug: false
}
},
scene: {
preload: preload,
create: create,
update: update
},
scale: {
autoCenter: Phaser.Scale.CENTER_BOTH
}
};
let game = new Phaser.Game(config);
let items = [];
function preload() {
for (let i = 1; i < 6; i++)
this.load.image(i, 'img/' + i + '.png');
}
function create() {
let x = 100;
let y = 0;
for (i = 0; i < 36; i++) {
if (i % 6 === 0) {
y += 85;
x = 100;
}
this.add.image(x, y, getRandomInt(5).toString())
x += 125;
}
}
function update() { }
function getRandomInt(max) {
return Math.floor(Math.random() * max) + 1;
}
</script>
</body>
</html>
I want something like this
I would just allow the user only to select (draw a line) to next valid circles.
A valid circle being, on the same row or same column or same color or max union length or ...
And when the drawing is finished I would, only allow union, when more than one circle is selected (is in the given path).
Here a short demo, how it could look like:
let config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width: 400,
height: 200,
banner: false,
scene: { create }
};
let game = new Phaser.Game(config);
let isDragging = false;
let lineStartPosition = {x:0 , y:0};
let currentPath = [];
let currentColor;
let line;
let pathGraphics;
function create ()
{
let cicles = []
for(let rowIdx = 0; rowIdx < 4; rowIdx++ ){
for(let colIdx = 0; colIdx < 2; colIdx++ ){
let circle = this.add.circle(50 + 100 * rowIdx, 50 + 100 * colIdx, 25, 0x6666ff).setOrigin(.5);
// Just to test a different color
if(rowIdx + colIdx ==2){
circle.fillColor = 0xff0000;
}
circle.setInteractive();
cicles.push(circle);
}
}
line = this.add.line(0,0, 0,0, 100, 100, 0xffffff).setOrigin(0);
line.setLineWidth(5);
line.visible = false;
pathGraphics = this.add.graphics();
// adding the events to the scene
this.input.on('pointerdown', dragStart);
this.input.on('pointerup', dragEnd);
this.input.on('pointermove', drag);
}
function dragStart(pointer, gameObjects){
if(gameObjects.length == 0){
return;
}
isDragging = true;
// remember Starting Color
currentColor = gameObjects[0].fillColor;
// initialize Path
currentPath = [gameObjects[0]];
// draw/save last segment of the path
lineStartPosition.x = gameObjects[0].x;
lineStartPosition.y = gameObjects[0].y;
line.x = gameObjects[0].x;
line.y = gameObjects[0].y;
line.setTo(0, 0, 0, 0);
line.visible = true;
}
function drag(pointer, gameObjects ){
if(isDragging == true){
// Check If Circle is allowed to be added, to path
// Here you would also check if the line is horizontal or vertical (this part is currently not implemented)
if(gameObjects[0] && currentPath.indexOf(gameObjects[0]) === -1 && currentColor == gameObjects[0].fillColor){
currentPath.push(gameObjects[0]);
line.x = gameObjects[0].x;
line.y = gameObjects[0].y;
lineStartPosition.x = gameObjects[0].x;
lineStartPosition.y = gameObjects[0].y;
}
line.setTo(0, 0, pointer.x - lineStartPosition.x, pointer.y - lineStartPosition.y);
drawPath();
}
}
function drawPath(){
pathGraphics.clear();
if(currentPath.length > 0){
pathGraphics.lineStyle(10, 0xffffff);
let path = new Phaser.Curves.Path(currentPath[0].x, currentPath[0].y);
for(let idx = 1; idx < currentPath.length; idx++){
let point = currentPath[idx];
path.lineTo(point.x, point.y);
}
path.draw(pathGraphics);
}
}
function dragEnd(pointer, gameObjects){
if(gameObjects.length == 0){
return;
}
if(currentPath.length < 2) {
console.info('No valid path');
return
} else {
console.info(`Valid Union path, length: ${currentPath.length}`);
}
line.visible = false;
isDragging = false;
}
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>

How to show two charts in the same html page

I'm working on a project where I should show two kind of charts :
a Real time Chart and I'm using smoothie.js lib for this.
a normal chart with zoom option and I'm using canvas lib for this.
as it showen in the code below the smoothie.js use on the body tag an "onload" :
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<title>Pression en temps réel</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="smoothie.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.bufferX = [];
setInterval(function () {
if( typeof lastid == 'undefined' ) {
$.get( "../be.php/lastid_1", function( dataA ) {
lastid = dataA[0].id_x+1;
})
}
else {
$.get( "../be.php/1&"+lastid, function( dataB ) {
var i =0;
var j=0;
if( typeof counter == 'undefined' ) {
counter = 0;
}
if( typeof pck_prev == 'undefined' ) {
pck_prev = -1;
}
lastid = dataB[0].last_id;
for(i=0;i<dataB.length;i++) {
for(j=0;j<dataB[i].data.length;j++) {
if(dataB[i].data[j] !== "" && dataB[i].data[j] !== 0 && typeof dataB[i].data[j] !== 'undefined' && pck_prev !== dataB[i].pck) {
window.bufferX.push(dataB[i].data[j]);
}
}
pck_prev = dataB[i].pck;
}
if(typeof window.bufferX[counter] == 'undefined') {
data_p.append(new Date().getTime(), window.bufferX[counter-1]);
}
})
}
},3000);
var data_p = new TimeSeries();
setInterval(function() {
if(window.bufferX.length>50 && counter <window.bufferX.length)
{
if( typeof counter == 'undefined' ) {
counter = 0;
}
else {
data_p.append(new Date().getTime(), window.bufferX[counter]);
counter++;
}
}
}, 250);
function createTimeline() {
var chart = new SmoothieChart({responsive: true});
chart.addTimeSeries(data_p, { strokeStyle: 'rgba(0, 255, 0, 1)', fillStyle: 'rgba(0, 255, 0, 0.2)', lineWidth: 4 });
chart.streamTo(document.getElementById("chart"), 250);
}
</script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
zoomEnabled: true,
title:{
text: "Try Zooming And Panning"
},
axisY:{
includeZero: false
},
data: data, // random generator below
});
chart.render();
}
var limit = 1000; //increase number of dataPoints by increasing this
var y = 0;
var data = []; var dataSeries = { type: "line" };
var dataPoints = [];
for (var i = 0; i < limit; i += 1) {
y += (Math.random() * 10 - 5);
dataPoints.push({
x: i - limit / 2,
y: y
});
}
dataSeries.dataPoints = dataPoints;
data.push(dataSeries);
</script>
</head>
<body onload="createTimeline()">
<canvas id="chart" style="width:100%; height:700px;"></canvas>
<div id="chartContainer" style="height: 700px; width: 100%;">
</div>
</body>
</html>
The problem is if I delete onload from body tag I will get the canvas chart only and if I let it I will get the real time chart only.
I would like to have both charts showen on my page.
Thanks for reading.
window.onload and <body onload="yourfunction();"> are different ways of using the same event and you are using both which is causing the issue. The easiest way to fix this problem is that you should write both the implementation in one event either in window.onload or in onload of body tag.
Find the updated fiddle here.
You can find both the chart are visible at the same time.

Geochart doesn't take any color

I wonder why geochart doesn't take any color from my code (take color value from Google sheet), not even defaultColor or colorAxis as you can see in the line that commented out,I have tried that all but it doesn't work.
The data in the Google sheet look like this:
Hope someone can help.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Map</title>
<style xmlns="http://www.w3.org/2000/svg">
#colormap path:hover { fill: #90db7c; }
#colormap rect:hover {fill:transparent;}
</style>
<script type='text/javascript' src='https://www.gstatic.com/charts/loader.js'></script>
<script src="https://www.google.com/jsapi"></script>
<script type='text/javascript'>
// Load Charts and the corechart package.
google.charts.load('current', {packages: ['geochart']});
// Callback that draws
function drawRegionsMap() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1dTfxVvfDKn6iXn4W_m7HJ_86JOGNDsxYSSaXipEo0vM/edit#gid=0');
// query.setQuery('select A,B,C');
query.send(handleQueryResponseTR);
}
function handleQueryResponseTR(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var colorValues = [];
var numRows = data.getNumberOfRows();
for (var i = 0; i < numRows; i++) {
colorValues.push(parseInt(data.getValue(i, 6)));
}
var view = new google.visualization.DataView(data);
//show data in tooltips
view.setColumns([0,{
type:'string',
label : 'dataname',
calc: function (dt, row) {
var dt1 = dt.getFormattedValue(row, 1)
var dt2 = dt.getFormattedValue(row, 2)
var url = dt.getFormattedValue(row, 4)
var image = dt.getFormattedValue(row, 5)
//colorValues.push(dt.getFormattedValue(row, 6))
return dt1 + " - " + dt2
},
role: 'tooltip',
p: {html: true}
}]);
//assign color to colorValues
var colorNames = [];
colorValues.forEach(function(value) {
if (value <= 2) {
colorNames.push('red');
//alert('red');
} else if ((value > 2) && (value <= 4)) {
colorNames.push('yellow');
//alert('yellow');
} else {
colorNames.push('green');
//alert('green');
}
});
var chart = new google.visualization.GeoChart(document.getElementById('colormap'));
google.visualization.events.addListener(chart, 'select', function () {
var selection = chart.getSelection();
if (selection.length > 0) {
//console.log(data.getValue(selection[0].row, 4));
window.open(data.getValue(selection[0].row, 4));
}
});
// Set options for the chart.
var options = {
defaultcolor: 'yellow'
//title:'WEEE',
//colorAxis: {
// values: [1, 2, 3, 4,5,6],
// colors: ['green', 'yellow', 'orange' ,'red','purple','lightblue'],
// };
//colors: colorNames,
//values: colorValues
// },
//backgroundColor: {fill:'#FFFFFF',stroke:'#FFFFFF' ,strokeWidth:0 },
//backgroundColor: '#FFFFFF',
//datalessRegionColor: '#F5F0E7',
//displayMode: 'regions',
//enableRegionInteractivity: 'true',
//resolution: 'countries',
//sizeAxis: {minValue: 1, maxValue:1,minSize:10, maxSize: 10},
//region:'world',
//keepAspectRatio: true,
//width:800,
//height:600,
//tooltip: {isHtml:'true',textStyle: {color: '#444444'} }
// };
}
chart.draw(view, options);
}
// Draw the chart when Charts is loaded.
google.charts.setOnLoadCallback(drawRegionsMap);
</script>
</head>
<body>
<div id='colormap'></div>
</body>
</html>

How to change background color of every single bubble in highcharts?

I am trying to get user inputs and then draw a bubble chart with 100 bubbles. How can I change the background color of bubbles to different colors(up to 10 colors)?
Below is my javascript code,
<script>
function generateChart() {
var my_arr = [];
var Stakeholders = [];
$('td').each(function () {
my_arr.push($(this).children().val());
});
var length = my_arr.length;
for (var i = 0; i < length - 2; i++) {
var Stakeholder = new Object();
Stakeholder.name = my_arr[i] || 'Unknown';
Stakeholder.x = parseFloat(my_arr[i + 1] || 5);
Stakeholder.y = parseFloat(my_arr[i + 2] || 5);
Stakeholders.push(Stakeholder);
i += 2;
}
drawChart(Stakeholders);
};
function drawChart(Stakeholders) {
Highcharts.chart('container', {
chart: {
type: 'bubble',
plotBorderWidth: 1,
zoomType: 'xy',
spacingTop: 40,
spacingRight: 40,
spacingBottom: 40,
spacingLeft: 40,
borderWidth: 1
},
plotOptions: {
column: {
colorByPoint: true
}
},
series: [{
data: Stakeholders
}]
});
};
</script>
I should have added a property to Stakeholder:
var colors = ['#98d9c2', '#ffd9ce', '#db5461', '#f5853f', '#b497d6', '#dc965a', '#FF9655', '#FFF263', '#6AF9C4', "000"];
for (var i = 0; i < length - 2 ; i++) {
var Stakeholder = new Object();
var color = parseInt(Math.random() * 10);
Stakeholder.name = my_arr[i] || 'Unknown';
Stakeholder.x = parseFloat(my_arr[i + 1]);
Stakeholder.y = parseFloat(my_arr[i + 2]);
Stakeholder.z = 5;
Stakeholder.color = colors[color];
Stakeholders.push(Stakeholder);
i += 2;
}
I'm not sure if you want to assign specific colors to specific bubbles or just randomly assign colors, but you can add a color: 'somecolor' property to each bubble object in the series.
Fiddle here (see lines 96-110).
Or, you could create an array of colors, loop through your bubble series, and randomly assign a color to each bubble object.
Hope this helps.

JavaScript Auto Updating Graph

Hello StackOverFlow I hate to bother you guys, but I really struggle with JavaScript and I am looking for a way to simply monitor this Javascript so that the Y variable is grabbed from one of my php files.
Example: http://foo.com/bar.php so I can have a live graph of my user data
Thank you so much for the help I appreciate it
The following code is the example JavaScript code which generates random data I guess.
/* Lines with autodrowing */
$(function () {
// we use an inline data source in the example, usually data would
// be fetched from a server
var data = [], totalPoints = 200;
function getRandomData() {
if (data.length > 0)
data = data.slice(1);
// do a random walk
while (data.length < totalPoints) {
var prev = data.length > 0 ? data[data.length - 1] : 50;
var y = prev + Math.random() * 10 - 5;
if (y < 0)
y = 0;
if (y > 100)
y = 100;
data.push(y);
}
// zip the generated y values with the x values
var res = [];
for (var i = 0; i < data.length; ++i)
res.push([i, data[i]])
return res;
}
// setup control widget
var updateInterval = 1000;
$("#updateInterval").val(updateInterval).change(function () {
var v = $(this).val();
if (v && !isNaN(+v)) {
updateInterval = +v;
if (updateInterval < 1)
updateInterval = 1;
if (updateInterval > 2000)
updateInterval = 2000;
$(this).val("" + updateInterval);
}
});
// setup plot
var options = {
yaxis: { min: 0, max: 100 },
xaxis: { min: 0, max: 100 },
colors: ["#aed267"],
series: {
lines: {
lineWidth: 2,
fill: true,
fillColor: { colors: [ { opacity: 0.4 }, { opacity: 0 } ] },
//"#dcecf9"
steps: false
}
}
};
var plot = $.plot($(".updating"), [ getRandomData() ], options);
function update() {
plot.setData([ getRandomData() ]);
// since the axes don't change, we don't need to call plot.setupGrid()
plot.draw();
setTimeout(update, updateInterval);
}
update();
});
I'm not sure of what your question is.
If you just want to get Y value from the serveur, do an ajax call :
var yVal;
$.ajax({
url:"/yourserv?action=getYValue",
success: function(data){
yVal = data;
}
});

Categories

Resources