简体   繁体   English

如何将 sympy 表达式转换为图形?

[英]How do I convert sympy expression into a graph?

How do I convert the following equation, as a function of f_ q (which is a function of 2D-vector q ) into a graphical representation?如何将作为 f_ q的函数(它是 2D 向量q的函数)的以下方程转换为图形表示?

在此处输入图片说明

It may be easier to consider something like y = sin(x) for the explanation however然而,考虑像 y = sin(x) 这样的解释可能更容易

I think you need to install matplotlib but then you should be able to do我认为你需要安装 matplotlib 但是你应该能够做到

>>> plot(x**2 + 1)

For your example you would have to give values for all parameters in order to see a plot wrt q, eg对于您的示例,您必须为所有参数提供值才能看到绘图 wrt q,例如

>>> plot(omega_q.subs([(omega0, 1), (Omega,2)]))

See the documentation on plotting in the doc/src/modules/plotting.rst请参阅 doc/src/modules/plotting.rst 中的绘图文档

Sympy has it's own plotting module . Sympy 有它自己的绘图模块 This module is mostly for convenience, to rapidly view a function without the need to leave sympy.该模块主要是为了方便,无需离开 sympy 即可快速查看功能。 There are very limited options for formatting.格式化的选项非常有限。

Plotting y=sin(x) is just:绘制y=sin(x)只是:

from sympy import plot, sin
from sympy.abc import x
plot(sin(x))

But that is only for 1D functions.但这仅适用于一维函数。 To plot 2D functions, matplotlib is the go-to library.要绘制 2D 函数, matplotlib首选库。 The simplest would be a 2D plot using color as a 3最简单的是使用颜色作为 3 的 2D 绘图dimension.尺寸。 Nicer and more informative plots can be got from 3D plots.可以从 3D 图中获得更好、信息更多的图。 Matplotlib standardly allows interacting with them to be viewed from different directions. Matplotlib 标准允许从不同方向查看与它们的交互。

Here is an example:下面是一个例子:

from sympy import sin, lambdify
from sympy.abc import x, y, a, b

f = sin(a*x*y+b) / (x*x+y*y+1)
# convert to a numpy function, make sure all variables apart from x and y have a fixed value
f_np = lambdify((x,y), f.subs({a: 1.5, b: 1}), 'numpy')


from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

x, y = np.meshgrid(np.linspace(-2,2,100), np.linspace(-2,2,100))
z = f_np(x, y)

fig = plt.figure()
ax = plt.axes(projection="3d")
ax.plot_surface(x, y, z, edgecolor='none', cmap='terrain')

plt.show()

示例图

See this interesting site for more ideas about 3d plotting.有关 3d 绘图的更多想法,请参见这个有趣的站点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM