Python 科学计算第二章图 2-4

代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['font.family'] = 'Helvetica Neue'


def triangle_wave(x, c, c0, hc):
    x = x - int(x)
    if x >= c:
        r = 0.0
    elif x < c0:
        r = x / c0 * hc
    else:
        r = (c - x) / (c - c0) * hc
    return r

x = np.linspace(0, 2, 10000)
y1 = np.array([triangle_wave(t, 0.6, 0.4, 1.0) for t in x])

triangle_ufunc1 = np.frompyfunc(triangle_wave, 4, 1)
y2 = triangle_ufunc1(x, 0.6, 0.4, 1)

triangle_ufunc2 = np.vectorize(triangle_wave, otypes=[np.float])
y3 = triangle_ufunc2(x, 0.6, 0.4, 1)

# Plot figures
plt.figure()
plt.title('Triangle Wave')
plt.xlabel('Time')
plt.ylabel('h')
plt.axis([0, 2, -0.3, 1.3])
plt.plot(x, y3, lw=2)

plt.plot([0.4, 0.4], [-0.05, 1], 'g--', dashes=[2, 2])
plt.plot([0.4, 0.75], [1, 1], 'g--', dashes=[2, 2])
plt.plot([0.6, 0.6], [-0.17, 0], 'g--', dashes=[2, 2])
dict = {"arrowstyle": "<->", "color": 'r', "shrinkA": 0, "shrinkB": 0,
        "connectionstyle": "arc3"}
plt.annotate("", (0, 0), (0.4, 0), arrowprops=dict)
plt.annotate("", (0, -0.12), (0.6, -0.12), arrowprops=dict)
plt.annotate("", (0.7, 0), (0.7, 1), arrowprops=dict)
plt.text(0.2, 0, '$c_0$', ha='center', va='bottom', size=15, color='r')
plt.text(0.3, -0.12, '$c$', ha='center', va='top', size=15, color='r')
plt.text(0.72, 0.5, '$hc$', ha='left', va='center', size=15, color='r')
plt.savefig('numpy_frompyfunc.pdf')
plt.show()

结果:

Image Title

  1. 字体

  2. numpy 提供的 frompyfuncvectorize

  3. 箭头,文字

2014-04-24 14:2252PythonNumpyMatplotlib
comments powered by Disqus