检索 SymPy 图的 matplotlib ContourSet

chr*_*hvz 5 python plot matplotlib sympy

使用 SymPy,我可以使用以下代码手动创建等高线图(还没有内置的等高线绘图功能 更新SymPy 现在具有等高线绘图功能):

from sympy import init_session
init_session()
from sympy.plotting.plot import Plot, ContourSeries

# show plot centered at 0,0
x_min = -7
x_max = 7
y_min = -5
y_max = 5

# contour plot of inverted cone
my_plot = Plot(
    ContourSeries(
        sqrt(x**2 + y**2),
        (x,x_min,x_max),
        (y,y_min,y_max)
    )
)
my_plot.show()
Run Code Online (Sandbox Code Playgroud)

等高线图 14x10

目前,当 SymPy 调用 时contour()它似乎没有保存返回的 ContourSet更新:我已经提交了一个问题,看看是否可以保存 ContourSet):

class MatplotlibBackend(BaseBackend):
    ...
    def process_series(self):  
        ... 
        for s in self.parent._series:
            # Create the collections
            ...
            elif s.is_contour:
                self.ax.contour(*s.get_meshes()) # returned ContourSet not saved by SymPy
Run Code Online (Sandbox Code Playgroud)

在对绘图执行修改的其他示例中,例如使用 添加内联标签clabel()CS需要ContourSet ( ):

# Create a simple contour plot with labels using default colors.
plt.figure()
CS = plt.contour(X, Y, Z) # CS is the ContourSet
plt.clabel(CS, inline=1, fontsize=10)
plt.title('Simplest default with labels')
Run Code Online (Sandbox Code Playgroud)

带标签的等高线图

回到 SymPy 示例,my_plot._backend确实提供了对图形和轴的访问;有哪些解决方法可以保留或获得对 ContourSet 的访问权限?

asm*_*rer 5

当 SymPy 的内置绘图功能无法满足您的需求时,一种选择是直接使用 matplotlib。关键是使用lambdifySymPy 表达式转换为 NumPy 函数。

f = lambdify((x, y), sqrt(x**2 + y**2), 'numpy')
Run Code Online (Sandbox Code Playgroud)

下面创建一个等高线图,作为cContourSet 对象。

a = numpy.linspace(-7, 7, 1000)
b = numpy.linspace(-5, 5, 1000)
x, y = numpy.meshgrid(a, b)
c = matplotlib.pyplot.contour(x, y, f(x, y))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述