将两个Sympy图显示为两个Matplotlib子图

rxztt3cl  于 12个月前  发布在  其他
关注(0)|答案(3)|浏览(89)

此代码

from sympy import *
x=Symbol('x')
p1 = plot(x**2,(x,-2,2))
p2 = plot(x**3,(x,-2,2))

字符串
导致两个单独的图。
我想用matplotlib将它们显示为子图,而不是两个单独的图:

import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
plt.show()


如何添加p1p2,使它们显示为matplotlib图中的子图?

bqucvtff

bqucvtff1#

问题是sympy Plot创建了自己的图形和轴。它并不意味着绘制到现有的轴。
但是,您可以在显示渐近图之前,用现有的轴替换绘制图的轴。

from sympy import Symbol,plot
import matplotlib.pyplot as plt

def move_sympyplot_to_axes(p, ax):
    backend = p.backend(p)
    backend.ax = ax
    backend._process_series(backend.parent._series, ax, backend.parent)  # backend.process_series() no longer works
    backend.ax.spines['right'].set_color('none')
    backend.ax.spines['bottom'].set_position('zero')
    backend.ax.spines['top'].set_color('none')
    plt.close(backend.fig)
    

x=Symbol('x')
p1 = plot(x**2,(x,-2,2), show=False)
p2 = plot(x**3,(x,-2,2), show=False)

fig, (ax,ax2) = plt.subplots(ncols=2)
move_sympyplot_to_axes(p1, ax)
move_sympyplot_to_axes(p2, ax2)

plt.show()

字符串


的数据

busg9geu

busg9geu2#

我的解决方案没有直接将p1p2添加到子图中,而是捕获并使用它们的(x,y)坐标。

import matplotlib.pyplot as plt
from sympy import symbols
import numpy as np

from sympy import symbols
from sympy.plotting import plot

# part 1
# uses symbolic plot of functions
x = symbols('x')

#p1, p2 = plot(x**2, x**3, (x, -2, 2))

# this plot will not show ...
# only produce 2 curves
p1, p2 = plot((x**2, (x, -2, 2)), \
                (x**3, (x, -2, 2)), \
                show=False)

# collect (x,y)'s of the unseen curves 
x1y1 = p1.get_points()  # array of 2D
x2y2 = p2.get_points() 

# part 2
# uses regular matplotlib to plot the data

fig = plt.figure(figsize=(8, 5))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

# do subplot 1 
ax1.plot(x1y1[0], x1y1[1], 'g')  # plot x**2 in green
ax1.set_xlim([-2, 2])
ax1.set_xlabel('X1')
ax1.set_ylabel('Y1')
ax1.set_title('Line1')  # destroyed by another .title(); axis metho1

# do subplot 2
ax2.plot(x2y2[0], x2y2[1], 'r')  # plot x**3 in red
ax2.set_xlim([-2, 2])
ax2.set_xlabel('X2')
ax2.set_ylabel('Y2')
ax2.set_title('Line2')

fig.subplots_adjust(wspace=0.4) # set space between subplots

plt.show()

字符串
结果图:


的数据

92vpleto

92vpleto3#

您可以简单地使用plotgrid在一个图中获得2个或多个图。
参见:sympy.plotting.PlotGrid()
下面是一个工作示例:

import sympy as sp
from matplotlib import pyplot as plt

# define functions
x = symbols('x')
f = sin(x)
g = cos(x)

# create separate plots
p1 = plot(f, show=False, xlim=(-pi, pi), line_color='blue', legend=True)
p2 = plot(g, show=False, xlim=(-pi, pi), line_color='red', legend=True)

# create a plotgrid with 2 rows and 1 column
plotgrid = sp.plotting.PlotGrid(2, 1, p1, p2, show=False, size=(5., 3.5))
plotgrid.show()

字符串
结果图:


的数据

相关问题