在iPython模块中获取用户输入以绘图的更好方法?

3 投票
1 回答
517 浏览
提问于 2025-04-16 17:32

我有一个模块要在iPython中使用。

我希望用户能输入绘图所需的所有内容,比如x、y、标签、线宽等等。

所以用户可能会这样做:

In[1] import this_script
In[2] x=range(0,10)
In[3] y=x
In[4] magically_exposed_function plot(x,y,'r+', linewidth=2)

这意味着我的函数会接收到字符串plot(x,y,'r+', linewidth=2)。这个字符串可以被解析,x和y的值可以通过ip.user_ns在iPython的命名空间中找到,但我还是不知道该怎么处理'r+'和linewidth=2。理想情况下,我希望能够:

a) 导入整个iPython命名空间,这样我就能获取到x和y的值;

b) 把整个字符串直接放进plot()函数里。

至于b),有类似这样的做法:

plot_string = x, y, 'r+', linewidth = 2
plot(plot_string)

那样就太好了,但上面的做法并不奏效。

这两件事有可能实现吗?有没有更优雅的解决方案?

用户是否可以直接使用plot(x,y),然后我的代码可以抓住这个图并进行编辑呢?

关于如何处理这种情况的任何建议都将非常感谢 :)

谢谢!

--Erin

[编辑] 这是我希望能够做到的演示:

import matplotlib
import wx
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanv
from matplotlib.figure import Figure
import IPython.ipapi
ip = IPython.ipapi.get()
import sys

class WrapperExample(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, None, -1)
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        self.axes.plot(*args, **kwargs)
        self.canvas = FigCanv(self, -1, self.figure)

def run_me(*args, **kwargs):
    """ Plot graph from iPython
    Example:
    In[1] import script
    In[2] x=range(0,10)
    In[3] y=x
    In[4] run_me x y
    """
    app = wx.PySimpleApp()
    wrap = WrapperExample(*args, **kwargs)
    wrap.Show()
    app.MainLoop()

ip.expose_magic("run_me", run_me)

[编辑] 以下是我最终使用下面建议的包装器的方法:

import wx
import matplotlib
from pylab import *
import IPython.ipapi
ip = IPython.ipapi.get()

class MainCanvas(wx.Frame):
    def __init__(self, *args):
        self.figure = plt.figure()
        self.axes = self.figure.add_subplot(111)
        self.axes.plot(*args)
        show()


def run_this_plot(self, arg_s=''):
    """ Run
    Examples
    In [1]: import demo
    In [2]: rtp x y <z> 
    Where x, y, and z are numbers of any type
    """
    args = []
    for arg in arg_s.split():
        try:
            args.append(self.shell.user_ns[arg])
        except KeyError:
            raise ValueError("Invalid argument: %r" % arg)
    mc = MainCanvas(*args)

# Activate the extension
ip.expose_magic("rtp", run_this_plot)

1 个回答

1

解析实际的字符串最好还是交给Python来处理。也许你可以考虑创建一个包装器:

real_plot = plot
def my_plot(*args, **kwargs):
    x, y = args[0], args[1]
    ...your extra code here...
    real_plot(*args, **kwargs)
plot = my_plot

撰写回答