让用户输入到iPython模块中绘图的更好方法?

2024-04-19 08:53:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模块要在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)

这意味着我的函数得到字符串图(x,y,'r+',linewidth=2)。可以对其进行分析并 在iPython命名空间中找到的x和y值使用ip.用户,但我还是被卡住了 如何处理“r+”和线宽=2。理想情况下,我希望能够:

a)导入整个iPython名称空间,使x和y的值可用,并且

b)将整个字符串放入plot()

至于b),有类似于:

^{pr2}$

会是理想的,但这不是上面所示的工作。在

这两件事都可以做吗?有没有更优雅的解决方案?在

用户是否可以绘制(x,y),而我的代码可以抓取该图并进行编辑?在

如有任何关于如何处理这种情况的建议,我们将不胜感激:)

谢谢! --艾琳

[编辑]演示我想做的事情:

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)

Tags: run用户infromimportselfipplot
1条回答
网友
1楼 · 发布于 2024-04-19 08:53:34

解析实际字符串最好留给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

相关问题 更多 >