问题
I'm trying to convert several python notebook file into python scripts so that I can create a python package... The problem I'm having now is that in python notebook, there's
%matplotlib notebook
magic button that makes user can click on a plot and receive the coordinate of the plot he/she just clicked on. The way to realize it is below:
f = urllib.urlopen(url_link)
fig = plt.figure(figsize=(3,3))
coords = coordinates(my_coord)[1]
image = plt.imread(f)
plt.imshow(image)
collector = {'x':0,'y':0}
def onclick(event):
collector['x'] = event.x
collector['y'] = event.y
cid = fig.canvas.mpl_connect('button_press_event',onclick)
print(collector)
Now I would like to make the same function in python script. but in script
%matplotlib notebook
is not working. Is there any alternative way that allows my python script do the same thing: showing plot and user can click on and return coordinate user clicked?
Thx in advance!
回答1:
In principle there is no need for such event handling, since this is automatically available in the matplotlib plotting window.
The following script
import matplotlib.pyplot as plt
image = plt.imread("image.jpg")
fig, ax = plt.subplots(figsize=(4,3))
ax.imshow(image)
plt.show()
produces this window
which shows the coordinates of the current mouse position inside the lower status bar.
But of course the functionality can be extended as in the question by using the same event handling mechanism
import matplotlib.pyplot as plt
image = plt.imread("image.jpg")
fig, ax = plt.subplots(figsize=(4,3))
ax.imshow(image)
collector = {'x':0,'y':0}
def onclick(event):
collector['x'] = event.x
collector['y'] = event.y
print(collector)
cid = fig.canvas.mpl_connect('button_press_event',onclick)
plt.show()
Note that this will print the figure coordinate, not the data coordinate. Since the figure coordinate is pretty useless in most cases, it would be better to use the data coordinates, like this.
collector['x'] = event.xdata
collector['y'] = event.ydata
Also see the event handling article on the matplotlib page.
来源:https://stackoverflow.com/questions/42541999/converting-functions-of-matplotlib-notebook-into-python-script