如何使用 sympy 图的标记参数?

How do I use the markers parameter of a sympy plot?

sympy plot 命令有一个 markers 参数:

markers : A list of dictionaries specifying the type the markers required. The keys in the dictionary should be equivalent to the arguments of the matplotlib's plot() function along with the marker related keyworded arguments.

如何使用 markers 参数?我失败的尝试范围从

from sympy import *
x = symbols ('x')
plot (sin (x), markers = 'o')

plot (sin (x), markers = list (dict (marker = 'o')))

不错的发现!

文档没有说清楚。深入研究源代码,导致 these lines in plot.py:

            for marker in parent.markers:
                # make a copy of the marker dictionary
                # so that it doesn't get altered
                m = marker.copy()
                args = m.pop('args')
                ax.plot(*args, **m)

所以,sympy 只调用 matplotlib 的 plot

  • 字典的args键作为位置参数
  • 字典的所有其他键作为关键字参数

由于 matplotlib 的 plot 允许参数种类繁多,因此这里都支持它们。它们主要是为了在绘图上显示额外的标记(您需要给出它们的位置)。

一个例子:

from sympy import symbols, sin, plot

x = symbols('x')
plot(sin(x), markers=[{'args': [2, 0, 'go']},
                      {'args': [[1, 3], [1, 1], 'r*'], 'ms': 20},
                      {'args': [[2, 4, 6], [-1, 0, -1], ], 'color': 'turquoise', 'ls': '--', 'lw': 3}])

这些转换为:

ax.plot(2, 0, 'go')  # draw a green dot at position 2,0
ax.plot([3, 5], [1, 1], 'r*', ms=20)  # draw red stars of size 20 at positions 3,1 and 5,1
ax.plot([2, 4, 6], [-1, 0, -1], ], color='turquoise', ls='--', lw=3)
    # draw a dotted line from 2,-1  over 4,0 to 6,-1

PS:源代码显示了一种类似的字典方法,带有注释、矩形和填充(使用 plt.fillbetween()):

        if parent.annotations:
            for a in parent.annotations:
                ax.annotate(**a)
        if parent.rectangles:
            for r in parent.rectangles:
                rect = self.matplotlib.patches.Rectangle(**r)
                ax.add_patch(rect)
        if parent.fill:
            ax.fill_between(**parent.fill)