converting functions of %matplotlib notebook into Python script

核能气质少年 提交于 2019-12-24 07:35:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!