views:

179

answers:

2

I return a chart image (with axis x and y) to the browser created my matplotlit. Now I want to show the axis values when there is mouseover event.

+2  A: 

Here's a solution using jQuery:

$('#myChart').mousemove(function(e){
    var x = e.pageX - this.offsetLeft;
    var y = e.pageY - this.offsetTop;
    // Do something with x and y;
});

See http://docs.jquery.com/Tutorials:Mouse_Position to learn more.

atxryan
+2  A: 

When I did something like this recently, I returned a PNG from matplotlib to the browser. I then applied an image-map to the PNG using the pixel values that correspond to the points plotted. I used an onmouseover event to pop up a 'tooltip' (actually just an absolute positioned div) that contained meta data about the point.

This article provided the foundation for my efforts but I remember there were certain hiccups in his implementation (mostly due to changes in the matplotlib api). If this question is still lingering around on Monday, I'll update this answer with specific code from my implementation (I don't have access to my work machines at the moment).

EDIT: As Promised Sample Code

import matplotlib.pyplot as plt

dpi = 96
fig = plt.figure(figsize=(8,8),dpi=dpi)
imgWidth = fig.get_figwidth() * dpi ## this is the actual pixel size of the plot
imgHeight = fig.get_figheight() * dpi ## this is the actual pixel size

my_lines = []
my_lines.append(plt.plot(Xs,Ys,marker='o')[0]) # add a line object to plot

mapHTML = '<MAP name="curveMap">'
for lineObj in my_lines:
  ## convert the points to pixel locations, for pop-ups
  lineObj._transform_path()
  path, affine = lineObj._transformed_path.get_transformed_points_and_affine()
  path = affine.transform_path(path)
  for real,pixel in zip(lineObj.get_xydata(),path.vertices):
    mapHTML+='''<AREA shape=\"circle\" coords=\"%i,%i,5\" href=\"javascript: void(0);\" onmouseout=\"outFly();\" onmouseover=\"javascript: popFly\(event,\\'%s\\',%i,%i\)\" />''' % (pixel[0],imgHeight-pixel[1],lineName,real[0],real[1])
mapHTML += '</MAP>'
fig.savefig(file(plot_file,"w"),format='png',dpi=dpi)
plt.close(fig)
plotHTML = '''<img src="/getPlot?uniq=%f" width="%i" height="%i" ismap usemap="#curveMap" onload="imageLoadCallback();" id="curPlot" />''' % (time.time(),imgWidth,imgHeight)
return "({'plotHTML':'%s','mapHTML':'%s'})" % (plotHTML,mapHTML)

You'll see that I'm writing the image to a png file and then returning JSON. I use javascript to update a DIV with the new img and image map.

Mark