【问题标题】:How do I use the markers parameter of a sympy plot?如何使用 sympy 图的标记参数?
【发布时间】:2022-11-27 02:16:42
【问题描述】:

sympy plot 命令有一个 markers 参数:

markers :字典列表,指定所需标记的类型。字典中的键应该等同于 matplotlib 的 plot() 函数的参数以及与标记相关的关键字参数。

如何使用markers参数?我失败的尝试包括

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

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

【问题讨论】:

    标签: python plot sympy markers


    【解决方案1】:

    不错的发现!

    文档没有说清楚。深入研究源代码,导致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)
    

    【讨论】:

      【解决方案2】:

      在交互式环境中,您可以使用 Matplotlib 后端将标记直接添加到轴图。

      以下在 Jupyter notebook 中运行。

      %matplotlib notebook
      import sympy as sp
      
      x = sp.symbols('x')
      p0 = sp.plot(sp.sin(x),(x,-sp.pi,sp.pi),show=False)
      p0.show()
      
      ax = p0._backend.ax[0]
      fig = p0._backend.fig
      
      x0 = float(sp.pi/2)
      y0 = float(sp.sin(sp.pi/2))
      
      ax.plot([x0,-x0],[y0,-y0],'r*',markersize=10)
      fig.show()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多