5

I am transitioning from Matlab to NumPy/matplotlib. A feature in matplotlib that seems to be lacking is interactive plotting. Zooming and panning is useful, but a frequent use case for me is this:

I plot a grayscale image using imshow() (both Matlab and matplotlib do well at this). In the figure that comes up, I'd like to pinpoint a certain pixel (its x and y coordinates) and get its value.

This is easy to do in the Matlab figure, but is there a way to do this in matplotlib?

This appears to be close, but doesn't seem to be meant for images.

Rich Li
  • 115
  • 2
  • 7

2 Answers2

2

I'm sure you have managed to do this already. Slightly(!) modifying the link, I've written the following code that gives you the x and y coordinates once clicked within the drawing area.

from pylab import * 
import sys
from numpy import *
from matplotlib import pyplot

class Test:

  def __init__(self, x, y):
    self.x = x
    self.y = y

  def __call__(self,event):
    if event.inaxes:
      print("Inside drawing area!")
      print("x: ", event.x)
      print("y: ", event.y)
    else:
      print("Outside drawing area!")

if __name__ == '__main__':     
  x = range(10)
  y = range(10)      
  fig = pyplot.figure("Test Interactive")
  pyplot.scatter(x,y)
  test = Test(x,y)
  connect('button_press_event',test)     
  pyplot.show()

Additionally, this should make it easier to understand the basics of interactive plotting than the one provided in the cookbook link.

P.S.: This program would provide the exact pixel location. The value at that location should give us the grayscale value of respective pixel.

Also the following could help: http://matplotlib.sourceforge.net/users/image_tutorial.html

Alma Rahat
  • 305
  • 3
  • 14
2

custom event handlers are what you are going to need for this. It's not hard, but it's not "it just works" either.

This question seems pretty close to what you are after. If you need any clarification, I'd be happy to add more info.

Community
  • 1
  • 1
Paul
  • 42,322
  • 15
  • 106
  • 123
  • That looks quite promising. I'll give it a try and let you know. I didn't find that question when I searched SO. For my purposes, I don't need interpolated values, so retrieving the values from the image array is the best method for me. I appreciate the extensibility of matplotlib, but it sure would be nice to have stuff like this built-in. – Rich Li Sep 30 '11 at 23:49
  • Sorry for the delay. Yes, your answer for that question has a pretty nifty event handler. It works well enough for my needs, although it would be even cooler to display the info in the status bar of the figure during mouseover instead of clicking. If I have the time/interest later, I'll see what I can do. – Rich Li Aug 10 '12 at 00:14