How to draw graph in java script? - javascript

I want to draw graph in java script. Let me share my problem with simple example.
Ind vs Aus cricket match.
X axis- Overs
Y axis- Runs
I want to show runs scored in each over by both teams in same graph. Can i show them together?
your experience will be useful to me. hoping for help.
would be grateful for help...thanks in advance,,

Try the Google Visualization API:
It includes classes to build datatables and then visualize them with different types of charts:
Example from the Google Visualiation Code Playground:
function drawVisualization() {
// Create and populate the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'x');
data.addColumn('number', 'Cats');
data.addColumn('number', 'Blanket 1');
data.addColumn('number', 'Blanket 2');
data.addRow(["A", 1, 1, 0.5]);
data.addRow(["B", 2, 0.5, 1]);
data.addRow(["C", 4, 1, 0.5]);
data.addRow(["D", 8, 0.5, 1]);
data.addRow(["E", 7, 1, 0.5]);
data.addRow(["F", 7, 0.5, 1]);
data.addRow(["G", 8, 1, 0.5]);
data.addRow(["H", 4, 0.5, 1]);
data.addRow(["I", 2, 1, 0.5]);
data.addRow(["J", 3.5, 0.5, 1]);
data.addRow(["K", 3, 1, 0.5]);
data.addRow(["L", 3.5, 0.5, 1]);
data.addRow(["M", 1, 1, 0.5]);
data.addRow(["N", 1, 0.5, 1]);
// Create and draw the visualization.
new google.visualization.LineChart(document.getElementById('visualization')).
draw(data, {curveType: "function",
width: 500, height: 400,
vAxis: {maxValue: 10}}
);
}
This will create a line chart with the X and Y axis which is what you are try to do.

gRaphael is a great choice for charts for web. It uses javascript to produce graphs in SVG and, in old versions of IE, VML, which makes it a great cross-browser starting point - it works in IE6 and above and doesn't need flash. Another good advantage is, using SVG/VML DOM elements controlled by a javascript object means your graph elements can be made highly interactive and manipulated in javascript at any time.
Example code (from doc barchart examples):
r.hbarchart(10, 250, 300, 220, [[55, 20, 13, 32, 5, 1, 2, 10], [10, 2, 1, 5, 32, 13, 20, 55]]).hover(fin, fout);
That line creates a two-variable bar chart which calls mousein and mouseout callback functions on each element which you could use to show related information e.g., in their example, the exact values. A two variable bar chart is probably a good way to represent two teams' scoring by over for one innings. A graphael dot chart might be a better good option if there are multiple overs and multiple innings - one for each team. There are other chart types supported too - see the demo examples on the main project page above.

Related

Tilemap collides with player and moves as one solid object (Phaser 3)

I have a tilemap that I'm generating from an array, (I can't use tiled, the game will be procedurally generated) that I need to collide with the player, but instead of the player colliding with the wall layer, when the player goes outside of the camera bounds and the tilemap and comes back in, they push the tilemap off the screen. My tilemap code is here, simplified. I'm guessing I need to be able to add blank tiles, but I'm not sure how.
var room = [
[1, 2, 2, 3],
[4, 0, 0, 8],
[4, 0, 0, 8],
[5, 6, 6, 7],];
this.map = this.make.tilemap({ data: room, tileWidth: 64, tileHeight: 64 });
var tiles = this.map.addTilesetImage("wall");
var layer = this.map.createLayer('wallLayer', tiles, 0, 0)
layer.setCollisionBetween(1, 8, true, true, layer)
this.physics.add.existing(layer)
this.physics.add.collider(layer, this.player)
Any help would be great, thanks!
The problem is, that you are adding the layer to the physics world with the line of code
this.physics.add.existing(layer);
in the file camp.js line 126
This is not needed! Since the two lines of code,
layer.setCollisionBetween(1, 16, true, false, layer); //(line 125)
this.physics.add.collider(layer, this.player); //(line 127)
in the file camp.js
set the collisions up between player and layer. No other action is needed to achieve collisions.

Drawing Lines on a Canvas from a For-Loop in Typescript doesnt render

I was making a graphing utility for fun, and then it turned into a real project...
I was trying to achieve a very simple graph... a line graph.
However, using a for-loop inside of my typescript project yields no results.
Look in the source code below, you can see I have console logs where I need to confirm an action is occuring. All of them run fine and in the perfect order in my typescript project.
Since SO doesnt support typescript, heres a codepen with the full source and typescript compiler: https://codepen.io/SkylerSpark/pen/zYvpWNZ
Snippet causing me the issues:
g.px & g.py are my coordinates. They are grabbed from this array (its an example array of pizza sales):
const pizzas = {
x: [0, 5, 10, 15, 20, 25, 30, 35, 40],
y: [0, 1, 2, 3, 4],
px: [0, 5.2, 7, 20.9, 34.3, 39.5],
py: [0, 1.1, 1.3, 2.7, 3.5, 3.9]
};
// Draw Numbers
if (g.px.length == g.py.length) {
console.log("confirm");
for (var i = 1; i < g.px.length + 1; i++) {
if (i == 1) {
console.log("start");
ctx.beginPath();
ctx.moveTo(g.px[i], g.py[i]);
} else if (i < g.px.length) {
console.log("continue");
ctx.lineTo(g.px[i], g.py[i]);
} else {
console.log("draw");
ctx.stroke();
}
console.log(i);
}
}
Now see the picture below, its running fine:
The problem is that your y-values need to be negative. In situations like these it's often useful to just draw any line instead of immediately using loops. I found this out by adding the following code
ctx.beginPath();
ctx.moveTo(-40, -40);
ctx.lineTo(40, -40);
ctx.lineTo(40, 40);
ctx.lineTo(-40, 40);
ctx.stroke();
just before you start drawing the line, which actually shows some results. If I change g.py[i] to -g.py[i] everywhere, then a small line is added to the bottom left of the graph. Hope this helps!

--AMI JS-- Creating segmentation LUT

I have a question regarding the use of segmentation LUTs in AMI JS (not XTK but there is no ami js tag yet!). Particularly what I want to do is to load a segmentation / labelmap layer and display it with the right colors, one for each label.
My labelmap layer consists of N integer labels that define different structures (e.g from 0 to 14000), which are also the voxel values of the labelmap. Each one of the labels has a different color associated (they are generated by Freesurfer and can be seen on: https://surfer.nmr.mgh.harvard.edu/fswiki/FsTutorial/AnatomicalROI/FreeSurferColorLUT ).
What I would like is a LUT that, for each different label, paints it with the correspondant color. I have had trouble finding the right way to do it and have not had success so far. What I have done is to get all the colors and store them into an array (colors normalized between 0 and 1 and the first component being the position inside the texture from 0 to 1, with a step of 1/total labels, which results in a really small step as there are 1200 labels!). From what I've seen then, the HelpersLUT class takes all the colors and maps them discretely into the texture, but the colors appear messed up and I can't seem to get the opacities right either...
I have seen also that the StackModels also have some functionalities such as prepareSegmentation() and such but do not know how to specify the LUT in there and cannot get it to work either (it is not used on the example).
Which is the best way to create a discrete LUT with a different color for each integer label and the 0 value being transparent and the other labels opaque?
The procedure used to generate the LUTs is: First I read a JSON with the information of the Freesurfer and store it into a variable, the first component of each one is the index of the label between 0 and 1, and the other ones are the associated color to the label between 0 and 1 as well. I have also generated a LUT of opacities.
let customLUT = {
"fsLUT": [],
"default": [[0, 0, 0, 0], [0.25, 0.3, 0.4, 0.5], [0.5, 0.2, 0.5, 0.4],
[0.75, 0.1, 0.2, 0.3], [1, 0.5, 0.5, 0.8]],
"fsLUT0": [[0, 0], [0.01, 1], [0.6, 1], [1, 1]]
};
$.getJSON("https://cdn.rawgit.com/YorkeUtopy/ami-viewerData/e773d737/FreesurferInfo.json", function (data) {
FsInfo = data;
FsInfo.forEach(function (value, i) {
customLUT.fsLUT.push([i / FsInfo.length, (value.color[0] / 255), (value.color[1] / 255.000), (value.color[2] / 255.000)]);
});
});
Then I create a helpers LUT with the LUT0 defined and the LUT with the colors and apply it to the texture. Everythink else is just as the labelmap example createing the layer mix, etc...
lutLayerLblmap = new HelpersLut(
"my-lut-canvases-l1",
"default",
"linear", [[0, 0, 0, 0], [1, 1, 1, 1]],
customLUT.fsLUT0,
false
);
lutLayerLblmap.luts = customLUT;
lutLayerLblmap.lut = "fsLUT";
refObj.uniformsLayerLblmap.uLut.value = 1;
refObj.uniformsLayerLblmap.uTextureLUT.value = lutLayerLblmap.texture;
With that some colors appear but there are not correct and the opacities are messed up (I know the LUT0 is not correct and that it is not discrete!). However, when I make the helpersLUT discrete and put a LUT0 like [0,0],[1,1], the colors are messed up and the opacities do not apply correctly... maybe it is that the voxel values are not between 0 and 1 but have values such as 1100,1200... ? or that I am not correctly generating the LUTs (step size too small?).... Here are some examples of the LUT.
[0]: 0,0,0,0
[1]:0.0008319467554076539,0.27450980392156865,0.5098039215686274,0.7058823529411765
[2]:0.0016638935108153079,0.9607843137254902,0.9607843137254902,0.9607843137254902
[3]:0.0024958402662229617,0.803921568627451,0.24313725490196078,0.3058823529411765
[last -2]:0.997504159733777,0.08235294117647059,0.7058823529411765,0.7058823529411765
[last-1]:0.9983361064891847,0.8745098039215686,0.8627450980392157,0.23529411764705882
[last]:0.9991680532445923,0.8666666666666667,0.23529411764705882,0.23529411764705882
this is the sample data I use:
T1 Volume + Labelmap + Freesurfer JSON
You seem to be making everything fine.
It is a current limitation in AMI side.
It currently only supports 256 colors and on top of that, it requires values to be normalized.
In AMI, we need to support a new type of LUT (Segmentation LUT seems a good name).
Live fiddle based on you approach.
const fsLUT = [];
fetch("https://cdn.rawgit.com/YorkeUtopy/ami-viewerData/e773d737/FreesurferInfo.json")
.then(response => response.json())
.then(jsonLUT => {
jsonLUT.forEach(function (value, i) {
fsLUT.push([
i / json.length,
(value.color[0] / 255),
(value.color[1] / 255.000),
(value.color[2] / 255.000)]);
});
return fsLUT;
})
http://jsfiddle.net/agoyre4e/20/

How can I show specific years in Google Timeline Chart?

Using react-google-charts, I would like to specify which years should be displayed on the horizontal axis of a Google Timeline Chart. The screenshot shows an example that uses automatically generated values, based on the given time range of the rows.
The example uses the following data:
[
[ 'Washington', new Date(1789, 3, 30), new Date(1797, 2, 4) ],
[ 'Adams', new Date(1797, 2, 4), new Date(1801, 2, 4) ],
[ 'Jefferson', new Date(1801, 2, 4), new Date(1809, 2, 4) ]
]
I already tried the following options with no joy:
hAxis: {
title: 'Year',
minValue: new Date(1785, 3, 15),
maxValue: new Date(1825, 3, 15),
ticks: [
{ v: new Date(1792, 3, 15), f: '1792' },
{ v: new Date(1818, 3, 15), f: '1818' },
{ v: new Date(1824, 3, 15), f: '1824' }
]
}
I would expect to have the x-Axis labelled with "Years" and showing 1792, 1818 and 1824 instead of 1790 and 1800.
The minValue and maxValue options seem to get ignored, too.
According to the readme it should be working.
Is the problem related to the value being date-objects instead of integers?
Edit: Added a jsfiddle: http://jsfiddle.net/s4zg7mxt/
It is not using react-google-charts, but the problem remains the same: ticks (and title) options still have no effect. Interestingly, the minValue and maxValue options are taken into account though.
Is it possible at all to adapt the jsfiddle, in order to show the specified years on the horizontal axis?
i've found if the configuration option, or other feature, isn't listed on the guide for that particular chart,
the chart doesn't support it.
except for options added in more recent releases,
in which the guide for that chart hasn't been updated.
as such, the only hAxis options available on a Timeline chart are minValue and maxValue
made available with the October 2, 2015 release
Timeline:
-- Durations are now localized.
-- Now supports minValue and maxValue for the horizontal axis.
The library automatically calculates the scaling of x-axis based on the start date, end date and browser's display area.
Please paste full code, will check and update you whether it is possible to do the custom scaling of the x-axis.

d3.js 3D array interpolation

Code is here: http://jsfiddle.net/S48QX/.
I want to draw a image based on a 3D data set, for example:
var data = [
{x:1.428, y:0.500, energy:0.458},
{x:1.428, y:1.191, energy:0.616},
{x:1.428, y:1.882, energy:0.795},
{x:1.428, y:2.573, energy:0.642},
{x:1.428, y:3.264, energy:0.536},
{x:1.428, y:3.955, energy:0.498},
{x:1.428, y:4.646, energy:0.494},
{x:1.428, y:5.337, energy:0.517},
...
}
It's like scattered plot, but I need every pixel to be set, not just a bunch of color dots on the image. So, my question is how can I interpolate scattered dots with d3.js.
The generated image here is the best I can do so far, but is it possible to make it more smooth and beautiful?
I am seeking a way to generate a HEATMAP only based on partial/scattered data. I hope there is a way in d3.js that can interpolate the missing part.
(1,5) ? ? ? (5,5)
? ? ? ? ?
? ? ? ? ?
(1,2) ? ? ? (5,2)
I have one solution using svg filters.
Be careful as this may not be what you want since the mathematical interpretation of this interpolation would be more 'blur'. I mostly did it as an exercise on svg filters. However 2d interpolation end up with similar results: see cubic interpolation for example (http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.interp2d.html in python)
I used circles (you could try with rectangles) slightly overlapping and semi transparent and applied to gaussian blur on them, resulting in a 'heatmap' looking thing.
var filter = svg.append("defs").append('filter')
.attr('id', 'blur')
.append("feGaussianBlur")
.attr("stdDeviation", 8);
then using .style('fill-opacity', 0.5).attr("filter", "url(#blur)") on the circles
See the fork http://jsfiddle.net/eqt1mkov/
With some effort you might be able to translate an existing algorithm to JavaScript.
Octave is open source and provides a method for scattered data interpolation:
http://www.dm.unibo.it/~achilles/calc/octave.html/Interpolation-on-Scattered-Data.html
The source code of Octave is available at
ftp://ftp.gnu.org/gnu/octave/
The file griddata.m and some referenced files can be found in the folder
octave_{version}\scripts\geometry
D3.js seems to provide some voronoi and delaunay functionality that might be helpful:
https://github.com/d3/d3/wiki/Voronoi-Geom
http://bl.ocks.org/mbostock/4341156
Python also provides a griddata method:
http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.griddata.html#scipy.interpolate.griddata
Plotly.js is based on D3.js and able to create contour plots for scattered data:
https://jsfiddle.net/vwksaob3/
var data = [ {
x: [0, 1, 1, 0],
y: [0, 0, 1, 1],
z: [0, 0, 1, 1],
type: 'contour',
colorscale: 'Jet',
showscale: false,
autocontour: true
}];
var layout = {
margin: {
b: 0,
l: 0,
r: 0,
t: 0
},
height: 600,
width: 600,
title: '',
xaxis: {
ticks: '',
showticklabels: false
},
yaxis: {
ticks: '',
showticklabels: false
}
};
Plotly.newPlot('graph', data, layout, {displayModeBar: false});

Categories