gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:54:20 24 4
gpt4 key购买 nike

我有一个要在 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)。这可以被解析和使用 ip.user_ns 在 iPython 命名空间中找到的 x 和 y 的值,但我仍然坚持如何处理 'r+' 和 linewidth=2。理想情况下,我希望能够:

a) 导入整个 iPython 命名空间,这样我就有了可用的 x 和 y 值,并且

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

至于 b),有类似的东西:

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

会很理想,但这并不如上所示。

这有可能做这些事情吗?有没有更优雅的解决方案?

用户是否可以执行 plot(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)

最佳答案

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

关于python - 获取用户输入以在 iPython 模块中绘图的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5983636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com