[英]How can I read new limits from a zoomed matplotlib.pyplot figure?
我有 2 个问题,在下面标记为 Q1、Q2。 Q1 是主要的,Q2 是次要的。 我想从放大的matplotlib.pyplot
图中读取新的限制。 也就是说,我希望发生以下步骤:
matplotlib.pyplot.plot
命令绘制完整集如果 Q2 为“否”,则步骤 (6-7) 将替换为另一个循环,其中图形在 (5) 中关闭并重新绘制并从 (1) 开始。 我可以接受,但更喜欢“Q2=yes”版本。
基于在调用 matplolib pyplot waitforbuttonpress() 时获取键值,我猜plt.waitforbuttonpress()
以某种方式参与,但我无法破译该链接中的建议。 我从来没有在 python 中使用过“事件”的东西。 我希望绘图窗口中已经有一些内置event
,我可以以某种方式访问它们吗? 示例代码:
import numpy as np
import matplotlib.pyplot as plt
N = 9999
dt = 0.1 / 180 * np.pi # 0.1 degree steps
tt = np.arange(0, N*dt, dt)
yy = np.sin(tt) + 0.05 * np.random.random(tt.shape) # include some noise
fig = plt.figure()
plt.plot(tt,yy)
plt.show()
# now the user zooms in... and questions Q1, Q2 apply.
好的,我找到了一个解决方案,虽然我觉得这很不美观。 我非常欢迎更好的解决方案。 这个对问题 Q1 和 Q2 都有效,但有两个缺点:(1) 它使用了一个全局变量,我被告知这是糟糕的编程 (?),以及 (2) 它给出了弃用警告。 代码修改的动机来自https://matplotlib.org/3.3.1/gallery/widgets/rectangle_selector.html (h/t @tmdavison)
import numpy as np
import matplotlib.pyplot as plt
def press_key_in_figure(event):
global xlimits
print("You pressed %s" % event.key)
if event.key == 'a':
xlimits = ax.get_xlim() # floats
print("new x-limits: %.2f %.2f" % xlimits)
if event.key == 'b':
ylimits = ax.get_ylim() # floats
print("new y-limits: %.2f %.2f" % ylimits)
xlimits = (0, 0)
N = 9999
dt = 0.1 / 180 * np.pi # 0.1 degree steps
tt = np.arange(0, N*dt, dt)
yy = np.sin(tt) + 0.05 * np.random.random(tt.shape) # include some noise
fig, ax = plt.subplots()
ax.plot(tt,yy)
fig.canvas.mpl_connect('key_press_event', press_key_in_figure)
plt.show()
# now the user zooms in... and questions Q1, Q2 apply.
print("The new x-limits after the window was closed are", xlimits)
当我运行它并缩放图片,然后按“a”或“b”时,它会给出:
C:\python\lib\tkinter\__init__.py:1705: MatplotlibDeprecationWarning: Toggling axes navigation from the keyboard is deprecated since 3.3 and will be removed two minor releases later.
return self.func(*args)
You pressed a
new x-limits: 3.62 6.48
You pressed b
new y-limits: -0.73 -0.23
我不确定“切换轴导航”是什么意思; 我没有在这里切换任何东西? 有趣的是,我的python --version
是 3.7.2,所以它似乎没有被删除,这与警告中声称的相反。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.