将%matplotlib笔记本的功能转换为Python脚本 [英] converting functions of %matplotlib notebook into Python script

查看:104
本文介绍了将%matplotlib笔记本的功能转换为Python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将多个python笔记本文件转换为python脚本,以便我可以创建python包... 我现在遇到的问题是在python笔记本中有

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)

现在,我想在python脚本中执行相同的功能.但在脚本中

Now I would like to make the same function in python script. but in script

%matplotlib notebook

不起作用.有没有其他方法可以让我的python脚本做同样的事情:显示图和用户可以单击并返回用户单击的坐标?

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?

提前谢谢!

推荐答案

原则上不需要这种事件处理,因为这可以在matplotlib绘图窗口中自动获得.

In principle there is no need for such event handling, since this is automatically available in the matplotlib plotting window.

以下脚本

import matplotlib.pyplot as plt

image = plt.imread("image.jpg")

fig, ax = plt.subplots(figsize=(4,3))
ax.imshow(image)

plt.show()

产生此窗口

它显示了状态栏下方当前鼠标位置的坐标.

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

另请参阅matplotlib页面上的事件处理文章.

Also see the event handling article on the matplotlib page.

这篇关于将%matplotlib笔记本的功能转换为Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆