`
xuanzhui
  • 浏览: 196980 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

通过matplotlib绘制心形

阅读更多

相关工具库很多,都是科学计算的东西:numpy、scipy、pandas、matplotlib、sympy、mayavi2

 

SciPy官网的介绍

http://www.scipy.org/getting-started.html

  • NumPy's array type augments the Python language with an efficient data structure useful for numerical work, e.g., manipulating matrices. NumPy also provides basic numerical routines, such as tools for finding eigenvectors.
  • SciPy contains additional routines needed in scientific work: for example, routines for computing integrals numerically, solving differential equations, optimization, and sparse matrices.
  • The matplotlib module produces high quality plots. With it you can turn your data or your models into figures for presentations or articles. No need to do the numerical work in one program, save the data, and plot it with another program.

 

简要的说:

numpy--定义了数值数组和矩阵类型和它们的基本运算的语言扩展

scipy--使用numpy来做高等数学、信号处理、优化、统计和许多其它科学任务的语言扩展

pandas--对numpy做了进一步封装

matplotlib--python的2D绘图库,提供了类MATLAB的API

mayavi2--python的3D绘图库 

sympy---python符号计算库

 

对sympy的解释比较抽象,运行实例感受一下

>>> import math,numpy,sympy
>>> math.sqrt(8)
2.8284271247461903
>>> math.sqrt(8) * math.sqrt(2)
4.000000000000001
>>> numpy.sqrt(8)
2.8284271247461903
>>> numpy.sqrt(8) * numpy.sqrt(2)
4.0000000000000009
>>> sympy.sqrt(8)
2*sqrt(2)
>>> sympy.sqrt(8) * sympy.sqrt(2)
4

 

 

以下内容只需要安装numpy、matplotlib和sympy

Windows安装numpy比较麻烦,有时可能遇到各种错,

可以直接去 http://www.lfd.uci.edu/~gohlke/pythonlibs/

搜索numpy,下载对应的系统预编译版本

下载完成用如下类似命令安装即可

pip install "numpy-1.10.4+mkl-cp35-none-win_amd64.whl"

 

 

1. 心形的公式

http://www.mathematische-basteleien.de/heart.htm

http://mathworld.wolfram.com/HeartCurve.html

http://mathworld.wolfram.com/HeartSurface.html




 

 

2. 绘制2D心形

1) 通过matplotlib

import matplotlib.pyplot as plt
import numpy as np

# -pi ~ pi, split 256
t = np.linspace(-np.pi, np.pi, 256, endpoint=True)
X = 16 * (np.sin(t))**3
Y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)

# plot at line1 column1
plt.subplot(121)

plt.plot(X, Y)

# -3 ~ 3, step 0.02
x = y = np.arange(-3.0, 3.0, 0.02)
X, Y = np.meshgrid(x, y)
Z = (X**2 + Y**2 - 1)**3 - X**2 * Y**3

# plot at line1 column2
plt.subplot(122)

plt.contour(X, Y, Z)
plt.colorbar()

plt.show()

 

2) 通过sympy

画等式特别方便

http://docs.sympy.org/latest/modules/plotting.html

>>> from sympy import symbols,plot_implicit
>>> x,y = symbols('x y')
>>> plot_implicit((x**2 + y**2 - 1)**3 - x**2 * y**3)

 

 

3. 绘制3D图形

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np

def heart_3d(x,y,z):
   return (x**2 + (9/4) * y**2 + z**2 - 1)**3 - x**2 * z**3 - (9/80) * y**2 * z**3

def heart_3d_2(x,y,z):
   return (2 * x**2 + 2 * y**2 + z**2 - 1)**3 - 0.1 * x**2 * z**3 - y**2 * z**3

def plot_implicit(fn, bbox=(-1.5, 1.5)):
    ''' create a plot of an implicit function
    fn  ...implicit function (plot where fn==0)
    bbox ..the x,y,and z limits of plotted interval'''
    xmin, xmax, ymin, ymax, zmin, zmax = bbox*3
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    A = np.linspace(xmin, xmax, 100) # resolution of the contour
    B = np.linspace(xmin, xmax, 40) # number of slices
    A1, A2 = np.meshgrid(A, A) # grid on which the contour is plotted

    for z in B: # plot contours in the XY plane
        X, Y = A1, A2
        Z = fn(X, Y, z)
        cset = ax.contour(X, Y, Z+z, [z], zdir='z', colors=('r',))
        # [z] defines the only level to plot
        # for this contour for this value of z

    for y in B:  # plot contours in the XZ plane
        X, Z = A1, A2
        Y = fn(X, y, Z)
        cset = ax.contour(X, Y+y, Z, [y], zdir='y', colors=('red',))

    for x in B: # plot contours in the YZ plane
        Y, Z = A1, A2
        X = fn(x, Y, Z)
        cset = ax.contour(X+x, Y, Z, [x], zdir='x',colors=('red',))

    # must set plot limits because the contour will likely extend
    # way beyond the displayed level.  Otherwise matplotlib extends the plot limits
    # to encompass all values in the contour.
    ax.set_zlim3d(zmin, zmax)
    ax.set_xlim3d(xmin, xmax)
    ax.set_ylim3d(ymin, ymax)

    plt.show()

if __name__ == '__main__':
    plot_implicit(heart_3d)

 

 

4. 最后通过turtle动态画一个心形

from turtle import *
def curvemove():
    for i in range(100):
        right(2)
        forward(2)

color('red','pink')        

begin_fill()

left(140)

forward(111.65)

curvemove()

left(120)

curvemove()

forward(111.65)

end_fill()

done()

 

refer

Plotting implicit equations in 3d

how to draw a heart with pylab

Is it possible to plot implicit equations using Matplotlib

Is it possible to plot implicit 3d equation using sympy

How can I draw a heart using Python

 

 

 

 

  • 大小: 4.9 KB
  • 大小: 10.8 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics