显示两个Sympy图作为两个Matplotlib子图 [英] Display two Sympy plots as two Matplotlib subplots

查看:59
本文介绍了显示两个Sympy图作为两个Matplotlib子图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码

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

产生两个单独的图.

我想用 matplotlib 作为子图显示它们,而不是两个单独的图:

Instead of two separate plots, I want to display them with matplotlib as subplots:

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

如何添加 p1 p2 ,以便将它们显示为matplotlib图形内的子图?

How can I add p1 and p2, so that they are displayed as subplots inside the matplotlib figure?

推荐答案

问题是sympy Plot 创建了自己的图形和轴.这并不意味着要绘制到现有的轴上.

The problem is that sympy Plot creates its own figure and axes. It is not meant to draw to an existing axes.

但是,您可以在显示sympy图之前用现有的轴替换绘制图的轴.

You may however replace the axes the plot is drawn to by an existing axes prior to showing the 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.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()

这篇关于显示两个Sympy图作为两个Matplotlib子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆