Get matplotlib ContourSet for SymPy Charts

Using SymPy, I can create a contour graph manually (there is no built-in contour plotting function yet) using the following code:

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()

contour graph 14x10

Currently, when SymPy calls contour(), it looks like it is not saving the returned ContourSet ( Update: I have a problem registered to see if ContourSet can be saved):

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

In other examples where modifications are made on the chart, for example, adding inline labels usingclabel() , ContourSet ( CS):

# 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')

outline graph with labels

Returning to the SymPy example, my_plot._backendprovides access to the shape and axes; What workarounds can I save or access the ContourSet?

+4
2

, SymPy , , - matplotlib. lambdify SymPy NumPy.

f = lambdify((x, y), sqrt(x**2 + y**2), 'numpy')

, c ContourSet.

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))

enter image description here

+3

, , . " " CS.collections[0].get_paths().

axes...

C , :

import numpy as np
import matplotlib.pylab as plt

X = np.arange(10)
Y = np.arange(10)
Z = np.random.random((10,10))

fig = plt.figure()
ax = fig.add_subplot(111)
A = ax.get_children()
cs = ax.contour (X, Y, Z)
B = ax.get_children()

C = [ref for ref in B if ref not in A]

fig2 = plt.figure()
ax2 = fig2.add_subplot(111)
ax2.add_collection(C[0])

fig: fig fig2: fig2

+1

Source: https://habr.com/ru/post/1666389/


All Articles