我正在编写宏来简化使用 matplotlib 制作绘图的过程。我的第一次尝试如下,正常工作:
(defmacro insert-ax [body] `((getattr g!ax (str '~(first body))) ~@(rest body)))
(defmacro/g! plot [main &optional title [fig-kwargs {}]]
`(do
(import [matplotlib.pyplot :as plt] [time [ctime]])
(setv [g!fig g!ax] (plt.subplots #**~fig-kwargs))
(insert-ax ~main)
(when ~title (.set-title g!ax ~title))
(.savefig g!fig (if ~title ~title (ctime)))))
然后以下代码按预期工作:
(plot (scatter xs ys) "Data"))
其中(在惯用的 Python 中)相当于
fig, ax = plt.subplots()
ax.scatter(xs,ys)
ax.set_title("Data")
fig.savefig("Data")
这很棒,但我希望能够传递多个表单,每个表单都可以转换,insert-ax
所以我可以添加多个图ax
,传递其他选项等。具体来说,这将是do-plot
这样的
(do-plot ((scatter xs ys) (scatter ys xs) "Data 2"))
相当于(再次在惯用的 Python 中)
fig, ax = plt.subplots()
ax.scatter(xs,ys)
ax.scatter(ys,xs)
ax.set_title("Data 2")
fig.savefig("Data 2")
但是以下幼稚的尝试不起作用:
(defmacro/g! do-plot [main &optional title [fig-kwargs {}]]
`(do
(import [matplotlib.pyplot :as plt] [time [ctime]])
(setv [g!fig g!ax] (plt.subplots #**~fig-kwargs))
(do (lfor cmd ~main (insert-ax cmd)))
(when ~title (.set-title g!ax ~title))
(.savefig g!fig (if ~title ~title (ctime)))))
这会返回一个NameError: name 'scatter' is not definedNameError: name 'scatter' is not defined
. 但这是可以理解的:main
在insert-ax
. 所以接下来的自然尝试:
现在我得到的错误是expanding macro do-plot NameError: name 'cmd' is not defined
. 这可能是因为main
为了使 lfor 循环/列表理解起作用,它没有被引用。所以下一步是尝试取消引用整个循环:
(defmacro/g! do-plot [main &optional title [fig-kwargs {}]]
`(do
(import [matplotlib.pyplot :as plt] [time [ctime]])
(setv [g!fig g!ax] (plt.subplots #**~fig-kwargs))
(do ~(lfor cmd main (insert-ax cmd)))
(when ~title (.set-title g!ax ~title))
(.savefig g!fig (if ~title ~title (ctime)))))
然后我的下一个错误是expanding macro do-plot AttributeError: 'HySymbol' object has no attribute 'c'
. 这似乎表明(因为 AttributeError 似乎与 相关getattr
)~(first body))
在 的定义中insert-ax
被评估为c
。
最后,出于对货物的狂热行为,我尝试了以下方法
(defmacro/g! do-plot [main &optional title [fig-kwargs {}]]
`(do
(import [matplotlib.pyplot :as plt] [time [ctime]])
(setv [g!fig g!ax] (plt.subplots #**~fig-kwargs))
(do ~@(lfor cmd main (insert-ax cmd)))
(when ~title (.set-title g!ax ~title))
(.savefig g!fig (if ~title ~title (ctime)))))
(尽管认为 unquote-splicing 会融合我的表格)。这会静默失败并且不会产生任何输出。然而,这里 hy2py 返回相同的错误expanding macro do-plot AttributeError: 'HySymbol' object has no attribute 'c'
我还能尝试什么?