Use the HoverTool in BokehJS - javascript

I wrote some javascript to create a correlation plot in BokehJS (everything happens in the client, I can't use the Python Bokeh package).
Now, I would like to add a HoverTool to display tooltips when the user hovers over the squares, but I can't find documentation or examples on how to do this. I started looking at the coffeescript source and found relavant pieces, but I don't really understand how to integrate them.
Any help finding documentation or examples about how to use the HoverTool in pure BokehJS would be great.

This is a pure javascript version that works with Bokeh 0.12.4.
It shows how to use grid plot, with separate hovers over each set of data.
The {0.01} in the hover object is used to format the values to 2 decimal places.
var plt = Bokeh.Plotting;
var colors = [
'#ee82ee', '#523ebf', '#9bc500', '#ffb600', '#f50019', '#511150',
'#8b38fa', '#2e792a', '#ffef00', '#ff7400', '#a90064', '#000000'
]
function circlePlots(xyDict, plot_width, plot_height, title) {
// make the plot and add some tools
var tools = "pan,crosshair,wheel_zoom,box_zoom,reset";
var p = plt.figure({
title: title,
plot_width: plot_width,
plot_height: plot_height,
tools: tools
});
// call the circle glyph method to add some circle glyphs
var renderers = [];
for (var i = 0; i <= 3; i += 1) {
// create a data source
var thisDict = {
'x': xyDict['x'],
'y': xyDict['y'][i],
'color': xyDict['color'][i]
}
var source = new Bokeh.ColumnDataSource({
data: thisDict
});
var r = p.circle({
field: "x"
}, {
field: 'y'
}, {
source: source,
fill_color: colors[i],
fill_alpha: 0.6,
radius: 0.2 + 0.05 * i,
line_color: null
});
renderers.push(r);
}
var tooltip = ("<div>x: #x{0.01}</div>" +
"<div>y: #y{0.01}</div>" +
"<div>color: #color</div>");
var hover = new Bokeh.HoverTool({
renderers: renderers,
tooltips: tooltip
});
p.add_tools(hover);
return p
}
var pageWidth = 450;
var plotCols = 2;
var plots = [];
var plotWidth = Math.floor(pageWidth / plotCols)
if (plotWidth > 600) {
plotWidth = 600
}
var plotHeight = Math.floor(0.85 * plotWidth)
for (var i = 0; i < plotCols; i += 1) {
// set up some data
var M = 20;
var xyDict = {
y: [],
color: []
};
for (var j = 0; j <= 4; j += 1) {
xyDict['x'] = [];
xyDict['y'].push([]);
xyDict['color'].push([]);
for (var x = 0; x <= M; x += 0.5) {
xyDict['x'].push(x);
xyDict['y'][j].push(Math.sin(x) * (j + 1) * (i + 1));
xyDict['color'][j].push(colors[j]);
}
}
var title = "Sin(x) Plot " + (i + 1).toString();
var p = circlePlots(xyDict, plotWidth, plotHeight, title);
plots.push(p)
};
plt.show(plt.gridplot([plots], sizing_mode = "stretch_both"));
<link href="https://cdn.bokeh.org/bokeh/release/bokeh-0.12.4.min.css" rel="stylesheet" />
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-0.12.4.min.js"></script>
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-api-0.12.4.min.js"></script>

First to use hover in bokeh you must add it as a tool and then personalise it to show what will be shown on hover. Look at this US Unemployment example from the bokeh docs
TOOLS = "hover,save"
p = figure(title="US Unemployment (1948 - 2013)",
x_range=years, y_range=list(reversed(months)),
x_axis_location="above", plot_width=900, plot_height=400,
toolbar_location="left", tools=TOOLS)
hover = p.select(dict(type=HoverTool))
hover.tooltips = OrderedDict([
('date', '#month #year'),
('rate', '#rate'),
])

Related

d3.csv working in jsfiddle not working on MTurk Worker Sandbox

I made a fiddle for testing my javascript. I was originally unable to grab csv data because the cross origin request header was not set for my google cloud bucket. Upon modifying the json header and pulling the data into my fiddle I got things working. Upon implementation within the MTurk Worker sandbox for testing my data no longer pulls into my handson table and furthermore no error is present in the console. I really am not sure what the issue would be so I am posting here as I have nothing to go off of. Any suggestions to search on would be much appreciated.
Additional Info: Chrome stopped working for my link with This page isn’t working
workersandbox.mturk.com redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS
however the HIT displays fine in firefox.
jsFiddle
Javascript
var csvLink = 'https://storage.googleapis.com/directionalsurvey/testDScsv.csv';
var data = [];
//var trueTVD = X6J374YZ;
var trueTVD = 700;
d3.csv(csvLink, function(dat) {
for (i = 0; i < dat.length; i++) {
var inner = [];
inner.push(dat[i]['Measured Depth']);
inner.push(dat[i]['Inclination']);
inner.push(dat[i]['Azimuth']);
data.push(inner);
}
var container1 = document.getElementById('Table'),
hot1;
var hot1 = new Handsontable(container1, {
data: data,
colHeaders: ['Measured Depth', "Inclination", "Azimuth"],
rowHeaders: true,
minSpareRows: 0,
contextMenu: ['row_above', 'row_below', 'remove_row']
});
function countRows() {
var ht = hot1
var rowcount = ht.countRows() - ht.countEmptyRows();
return rowcount;
}
$("#get_data").click(submitForm);
/////////////////////////////////////////Begin Functions for Minimum Curvature Algorithm////////////////////////////
function Beta(I1, I2, Az1, Az2) {
var dI = Deg2Rad(I2) - Deg2Rad(I1);
var dA = Deg2Rad(Az2) - Deg2Rad(Az1);
var X = math.sin(Deg2Rad(I1)) * math.sin(Deg2Rad(I2));
var Y = math.cos(dI);
var Z = math.cos(dA);
var beta = math.acos(Y - (X * (1 - Z)));
return beta;
}
function RF(beta) {
var b = beta;
var rf = (2 / b) * math.tan(b / 2);
return rf;
}
function TVD(dmd, I1, I2, RF) {
var A = math.cos(Deg2Rad(I1)) + math.cos(Deg2Rad(I2));
var tvd = (dmd / 2) * A * RF;
return tvd;
}
function Deg2Rad(deg) {
return deg * math.pi / 180;
}
function Rad2Deg(rad) {
return rad * 180 / math.pi
}
// function to calculate the TVD
function TVDcalc(MD, INC, AZI, Depth) {
var md = MD;
var inc = INC;
var azi = AZI;
var i;
for (i = 0; i < md.length - 1; i++) {
var beta = Beta(inc[i], inc[i + 1], azi[i], azi[i + 1]);
if (inc[i] == inc[i + 1]) {
var rf = 1;
} else {
var rf = RF(beta);
}
var dMD = md[i + 1] - md[i];
Depth.push(TVD(dMD, inc[i], inc[i + 1], rf) + Depth[i]);
}
return Depth
}
/////////////////////////////////////////End Functions for Minimum Curvature Algorithm////////////////////////////
function enable(TVD) {
if (TVD[TVD.length - 1] >= trueTVD - 5 && TVD[TVD.length - 1] <= trueTVD + 5) {
//console.log(TVD[TVD.length - 1]);
$('#submitButton').prop("disabled", false);
} else {
$('#submitButton').prop("disabled", true);
}
}
function submitForm() {
var htContents = hot1.getSourceData() //getSourceData(1,1,countRows(),3)
//console.log(htContents);
var md = [];
var inc = [];
var azi = [];
var Depth = [];
var fd = Number($('#TVD1').val())
Depth.push(fd);
//transform the HOT into individual arrays for ingestion in TVD calc
for (i = 0; i < countRows(); i++) {
md.push(htContents[i][0]);
inc.push(htContents[i][1]);
azi.push(htContents[i][2]);
}
var TVD = TVDcalc(md, inc, azi, Depth)
enable(TVD);
console.log("".concat("Calculated TVD: ", Math.round(Depth[Depth.length - 1])));
console.log("".concat("Expected TVD: ", trueTVD))
}
});
d3.csv is asynchronous in nature, the question d3: make the d3.csv function syncronous answers my question however I ended up just using ajax instead.

Creating an javascript graph with marker that is synchronize with a movie

I'm trying to create an online web tool for eeg signal analysis. The tool suppose to display a graph of an eeg signal synchronize with a movie that was display to a subject.
I've already implemented it successfully on csharp but I can't find a way to do it easily with any of the know javascript chart that I saw.
A link of a good tool that do something similar can be found here:
http://www.mesta-automation.com/real-time-line-charts-with-wpf-and-dynamic-data-display/
I've tried using dygraph, and google chart. I know that it should be relatively easy to create an background thread on the server that examine the movie state every ~50ms. What I was not able to do is to create a marker of the movie position on the chart itself dynamically. I was able to draw on the dygraph but was not able to change the marker location.
just for clarification, I need to draw a vertical line as a marker.
I'm in great suffering. Please help :)
Thanks to Danvk I figure out how to do it.
Below is a jsfiddler links that demonstrate such a solution.
http://jsfiddle.net/ng9vy8mb/10/embedded/result/
below is the javascript code that do the task. It changes the location of the marker in synchronizing with the video.
There are still several improvement that can be done.
Currently, if the user had zoomed in the graph and then click on it, the zoom will be reset.
there is no support for you tube movies
I hope that soon I can post a more complete solution that will also enable user to upload the graph data and video from their computer
;
var dc;
var g;
var v;
var my_graph;
var my_area;
var current_time = 0;
//when the document is done loading, intialie the video events listeners
$(document).ready(function () {
v = document.getElementsByTagName('video')[0];
v.onseeking = function () {
current_time = v.currentTime * 1000;
draw_marker();
};
v.oncanplay = function () {
CreateGraph();
};
v.addEventListener('timeupdate', function (event) {
var t = document.getElementById('time');
t.innerHTML = v.currentTime;
g.updateOptions({
isZoomedIgnoreProgrammaticZoom: true
});
current_time = v.currentTime * 1000;
}, false);
});
function change_movie_position(e, x, points) {
v.currentTime = x / 1000;
}
function draw_marker() {
dc.fillStyle = "rgba(255, 0, 0, 0.5)";
var left = my_graph.toDomCoords(current_time, 0)[0] - 2;
var right = my_graph.toDomCoords(current_time + 2, 0)[0] + 2;
dc.fillRect(left, my_area.y, right - left, my_area.h);
};
//data creation
function CreateGraph() {
number_of_samples = v.duration * 1000;
// A basic sinusoidal data series.
var data = [];
for (var i = 0; i < number_of_samples; i++) {
var base = 10 * Math.sin(i / 90.0);
data.push([i, base, base + Math.sin(i / 2.0)]);
}
// Shift one portion out of line.
var highlight_start = 450;
var highlight_end = 500;
for (var i = highlight_start; i <= highlight_end; i++) {
data[i][2] += 5.0;
}
g = new Dygraph(
document.getElementById("div_g"),
data, {
labels: ['X', 'Est.', 'Actual'],
animatedZooms: true,
underlayCallback: function (canvas, area, g) {
dc = canvas;
my_area = area;
my_graph = g;
bottom_left = g.toDomCoords(0, 0);
top_right = g.toDomCoords(highlight_end, +20);
draw_marker();
}
});
g.updateOptions({
clickCallback: change_movie_position
}, true);
}

NVD3 - How to refresh the data function to product new data on click

I have a line chart and every time the page refresh it changes the data, which is great but I need to to refresh by a user click. This is because there will eventually be other input fields on the page and refreshing the page would destroy their current session.
jsfiddle - http://jsfiddle.net/darcyvoutt/dXtv2/
Here is the code setup to create the line:
function economyData() {
// Rounds
var numRounds = 10;
// Stability of economy
var stable = 0.2;
var unstable = 0.6;
var stability = unstable;
// Type of economy
var boom = 0.02;
var flat = 0;
var poor = -0.02;
var economyTrend = boom;
// Range
var start = 1;
var max = start + stability;
var min = start - stability;
// Arrays
var baseLine = [];
var economy = [];
// Loop
for (var i = 0; i < numRounds + 1; i++) {
baseLine.push({x: i, y: 1});
if (i == 0) {
economyValue = 1;
} else {
var curve = Math.min(Math.max( start + ((Math.random() - 0.5) * stability), min), max);
economyValue = Math.round( ((1 + (economyTrend * i)) * curve) * 100) / 100;
}
economy.push({x: i, y: economyValue});
}
return [
{
key: 'Base Line',
values: baseLine
},
{
key: 'Economy',
values: economy
}
];
}
Here is what I tried to write but failed for updating:
function update() {
sel = svg.selectAll(".nv-line")
.datum(data);
sel
.exit()
.remove();
sel
.enter()
.append('path')
.attr('class','.nv-line');
sel
.transition().duration(1000);
};
d3.select("#update").on("click", data);
Here is what I did differently with your code.
// Maintian an instance of the chart
var chart;
// Maintain an Instance of the SVG selection with its data
var chartData;
nv.addGraph(function() {
chart = nv.models.lineChart().margin({
top : 5,
right : 10,
bottom : 38,
left : 10
}).color(["lightgrey", "rgba(242,94,34,0.58)"])
.useInteractiveGuideline(false)
.transitionDuration(350)
.showLegend(true).showYAxis(false)
.showXAxis(true).forceY([0.4, 1.6]);
chart.xAxis.tickFormat(d3.format('d')).axisLabel("Rounds");
chart.yAxis.tickFormat(d3.format('0.1f'));
var data = economyData();
// Assign the SVG selction
chartData = d3.select('#economyChart svg').datum(data);
chartData.transition().duration(500).call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
Here's how the update() function looks like:
function update() {
var data = economyData();
// Update the SVG with the new data and call chart
chartData.datum(data).transition().duration(500).call(chart);
nv.utils.windowResize(chart.update);
};
// Update the CHART
d3.select("#update").on("click", update);
Here is a link to a working version of your code.
Hope it helps.

For Loop MovieClip Grid not showing on stage

So I'm a newbie and should obviously spend time in the tuts, but I'm looking for a quick answer. Basically, I've created a grid of movie clips with AS3. When I 'preview' the flash (as a flash or HTML) it shows up fine. Success. Yet, the stage remains empty.
Q1) Will the stage remain empty as I have used AS3 to dynamically 'draw' the grid of mc's? Or is there a slit of code I am missing to make this baby show up on the stage?
Q2) I've managed to use alpha to make the MC's 'fade' on hover - but I want to make them change color (to red) when hovered over. I've searched everywhere and can't seem to find the right script.
Here is my code:
var stage = new createjs.Stage("canvas");
var image = new createjs.Bitmap("images/square.png");
stage.addChild(image);
createjs.Ticker.addEventListener("tick", handleTick);
function handleTick(event) {
image.x += 10;
stage.update();
}
var x0:Number = 0;
var y0:Number = 0;
var nt:Number = 72;
var nc = 10;
var vd:Number = 12;
var hd:Number = 12;
for (var i = 1; i <= nt; i++) {
var mc = this.attachMovie("square", "square" + i, i);
var aprox = Math.floor((i - 1) / nc);
mc._x = x0 + hd * ((i - aprox * nc) - 1);
mc._y = y0 + aprox * vd;
mc.useHandCursor = true;
// fade in
mc.onRollOver = function()
{
this.onEnterFrame = function()
{
if (this._alpha > 0) {
this._alpha -= 10;
} else {
this._alpha = 0;
delete this.onEnterFrame;
}
};
};
// fade out
mc.onRollOut = function()
{
this.onEnterFrame = function()
{
if (this._alpha < 100) {
this._alpha += 10;
} else {
this._alpha = 100;
delete this.onEnterFrame;
}
};
};
}
Thanks in advance - sorry I am a noob.
This will never work. 1/3 of your code is in AS3, 2/3 in AS2. Considering you haven't been thrown any error, I assume you exported it as AS2.

Changing the draw attributes of a vector feature in open layers

I am loading a shapefile from a server and than drawing it n OpenLayers. The shapefile contains over 400,000 multipolygons with varying opacity. I need to set the opacity and fill color yet openlayers seems to be ignoring it and just drawing orange squares instead. I console.log() before I change the attributes and after and it shows what I assigned it. Can anyone tell me why it is doing that?
var green = {
fill: true,
fillColor: "#006633",
fillOpacity: 1
};
var features = wkt.read(element);
if (featureNumber == 0){
document.getElementById('result').innerHTML=element;
}
features = element.toString();
var bounds;
var b = features.indexOf('MULTIPOLYGON', 0);
var c = features.indexOf('MULTIPOLYGON', 40);
if (c == -1) {
c = element.indexOf(':',b+1);
}
leftovers = features.substring(c,100000000000000000);
features = features.substring(b,c);
features = wkt.read(features);
if(features) {
if(features.constructor != Array) {
features = [features];
}
for(var i=0; i<features.length; ++i) {
if (!bounds) {
bounds = features[i].geometry.getBounds();
} else {
bounds.extend(features[i].geometry.getBounds());
}
}
pointLayer.addFeatures(features);
console.log(pointLayer.features[featureNumber].attributes );
pointLayer.features[featureNumber].attributes = green;
console.log(pointLayer.features[featureNumber].attributes );
featureNumber++
map.zoomToExtent(bounds);
var plural = (features.length > 1) ? 's' : '';
console.log('Feature' + plural + ' added');
console.log('feature number: '+featureNumber)
if (leftovers.indexOf('MULTIPOLYGON',0) != -1) {
parseWKT(leftovers,shapefile);
}
} else {
final(leftovers, shapefile);
}
}
well the style belongs in the .style property not the .attributes of the feature. You'll also need to call redraw() if it's already on the map.
pointLayer.features[featureNumber].style = green;
pointLayer.redraw();
If you want to start out with the default style and just change a few things, you can do something like this:
var green = OpenLayers.Util.applyDefaults(green, OpenLayers.Feature.Vector.style['default']);
green.fill = true;
green.fillColor = "#006633";
green.fillOpacity = 1;
pointLayer.features[featureNumber].style = green;
pointLayer.redraw();

Categories

Resources