由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址

Matplotlib

1. Quick Start

1.1 Quick hit

  1. import numpy as np
  2. import matplotlib as mpl
  3. import matplotlib.pyplot as plt
  4. np.random.seed(1000)
  5. y = np.random.standard_normal(20)
  6. x = range(len(y))
  7. plt.plot(x, y)
  8. plt.show()

Matplotlib - 图1

1.2 Adding layers

  1. ## Showing change of each movements
  2. plt.ion()
  3. plt.show()
  4. np.random.seed(2000)
  5. y = np.random.standard_normal((20,2)).cumsum(axis=0)
  6. plt.figure(figsize=(7, 4)) # adding a canves figsize=(width, height)
  7. plt.plot(y.cumsum(), 'm',lw=1.5) # adding a line
  8. plt.plot(y.cumsum(), 'ro') # adding dots
  9. plt.grid(True) # adding grid on panals
  10. plt.axis('tight') # adding... I don't know
  11. plt.xlabel('index') # adding a title x
  12. plt.ylabel('value') # addint a title y
  13. plt.title('A Simple Plot') # adding a title

Matplotlib - 图2

1.3 Facet(subplot)

  1. plt.ion()
  2. plt.show()
  3. ## Data set
  4. np.random.seed(2000)
  5. y = np.random.standard_normal((20,2)).cumsum(axis=0)
  6. plt.figure(figsize=(7,5))
  7. plt.subplot(211)
  8. '''
  9. 211:
  10. 2: 2 plot in a column;
  11. 1: 1 plot in a row
  12. 1: the 1sd
  13. '''
  14. plt.plot(y[:, 0], lw=1.5, label='1st')
  15. plt.plot(y[:, 0], 'ro')
  16. plt.grid(True)
  17. plt.legend(loc=0)
  18. plt.axis('tight')
  19. plt.ylabel('value')
  20. plt.title('A Simple Plot')
  21. plt.subplot(212) # the second
  22. plt.plot(y[:, 1], 'g', lw=1.5, label='2nd')
  23. plt.plot(y[:, 1], 'ro')
  24. plt.grid(True)
  25. plt.legend(loc=0)
  26. plt.axis('tight')
  27. plt.xlabel('index')
  28. plt.ylabel('value')

Matplotlib - 图3

2. Main Plot

2.1 Dot plot

  1. plt.plot(y[:, 0], 'ro')

2.2 Scatter plot

2.2.1 plot()

  1. y = np.random.standard_normal((1000, 2))
  2. plt.figure(figsize=(7, 5))
  3. plt.plot(y[:, 0], y[:, 1], 'ro')
  4. plt.grid(True)
  5. plt.title('Scatter Plot')

Matplotlib - 图4

2.2.2 scatter()

  1. plt.figure(figsize=(7, 5))
  2. plt.scatter(y[:, 0], y[:, 1], marker='o')
  3. plt.grid(True)
  4. plt.xlabel('1st')
  5. plt.ylabel('2nd')
  6. plt.title('Scatter Plot')

2.2.3 Adding color: c = c

  1. c = np.random.randint(0, 10, len(y))
  2. plt.figure(figsize=(7, 5))
  3. plt.scatter(y[:, 0], y[:, 1], c=c, marker='o')
  4. plt.colorbar()
  5. plt.grid(True)
  6. plt.xlabel('1st')
  7. plt.ylabel('2nd')
  8. plt.title('Scatter Plot')

Matplotlib - 图5

2.3 Line plot

  1. y = np.random.standard_normal(20)
  2. x = range(len(y))
  3. plt.plot(y, lw=1.5, label='1st')

2.4 Bar plot

2.4.1 Bar plot

  1. y = np.random.standard_normal(20)
  2. x = range(len(y))
  3. plt.bar(np.arange(len(y)), y, width=0.5, color='g', label='2nd')

Matplotlib - 图6

2.4.2 Histogram

1. Align as “dodge”
  1. plt.figure(figsize=(7, 4))
  2. plt.hist(y, label=['1st', '2nd'], bins=25)
  3. plt.grid(True)
  4. plt.legend(loc=0)
  5. plt.xlabel('value')
  6. plt.ylabel('frequency')
  7. plt.title('Histogram')

Matplotlib - 图7

2. Align as ‘stack’
  1. y = np.random.standard_normal((1000, 2))
  2. plt.figure(figsize=(7, 4))
  3. plt.hist(y, label=['1st', '2nd'], color=['b', 'g'], stacked=True, bins=20)
  4. plt.grid(True)
  5. plt.legend(loc=0)
  6. plt.xlabel('value')
  7. plt.ylabel('frequency')
  8. plt.title('Histogram')

Matplotlib - 图8

2.5 Box polt

  1. fig, ax = plt.subplots(figsize=(7,4))
  2. plt.boxplot(y)
  3. plt.grid(True)
  4. plt.setp(ax, xticklabels=['1st', '2nd'])
  5. plt.xlabel('data set')
  6. plt.ylabel('value')
  7. plt.title('Boxplot')

Matplotlib - 图9

2.6 Adding Text/Formula

  1. from matplotlib.patches import Polygon
  2. def func(x):
  3. return 0.5 * np.exp(x) + 1
  4. a, b = 0.5, 1.5
  5. x = np.linspace(0, 2)
  6. y = func(x)
  7. fig, ax = plt.subplots(figsize=(7, 5))
  8. plt.plot(x, y, 'b', linewidth=2)
  9. plt.ylim(ymin=0)
  10. Ix = np.linspace(a, b)
  11. Iy = func(Ix)
  12. verts = [(a, 0)] + list(zip(Ix, Iy)) + [(b, 0)]
  13. poly = Polygon(verts, facecolor='0.7', edgecolor='0.5')
  14. ax.add_patch(poly)
  15. plt.text(0.5 * (a + b), 1, r"$\int_a^b fx\mathrm{d}x$", horizontalalignment='center', fontsize=20)
  16. plt.figtext(0.9, 0.075, '$x$')
  17. plt.figtext(0.075, 0.9, '$f(x)$')
  18. ax.set_xticks((a, b))
  19. ax.set_xticklabels(('$a$', '$b$'))
  20. ax.set_yticks([func(a), func(b)])
  21. ax.set_yticklabels(('$f(a)$', '$f(b)$'))
  22. plt.grid(True)

Matplotlib - 图10
Result

3. Plot 3D

3.1

  1. ## Preparing for Data set
  2. strike = np.linspace(50, 150, 24)
  3. ttm = np.linspace(0.5, 2.5, 24)
  4. strike, ttm = np.meshgrid(strike, ttm)
  5. iv = (strike - 100) ** 2 / (100 * strike) / ttm
  6. from mpl_toolkits.mplot3d import Axes3D
  7. fig = plt.figure(figsize=(9,6))
  8. ax = fig.gca(projection='3d')
  9. surf = ax.plot_surface(strike, ttm, iv, rstride=2, cstride=2, cmap=plt.cm.coolwarm, linewidth=0.5, antialiased=True)
  10. ax.set_xlabel('strike')
  11. ax.set_ylabel('time-to-maturity')
  12. ax.set_zlabel('implied volatility')
  13. fig.colorbar(surf, shrink=0.5, aspect=5)

Matplotlib - 图11

3.2 switch to dot

  1. fig = plt.figure(figsize=(8, 5))
  2. ax = fig.add_subplot(111, projection='3d')
  3. ax.view_init(30, 60)
  4. ax.scatter(strike, ttm, iv, zdir='z', s=25, c='b', marker='^')
  5. ax.set_xlabel('strike')
  6. ax.set_ylabel('time-to-maturity')
  7. ax.set_zlabel('implied volatility')

Matplotlib - 图12

Save

  1. ## Assignment the size of the picture
  2. plt.figure(figsize=(12*3, 8*3))
  3. ## Save
  4. plt.savefig(OUTPUT)

Enjoy~

本文由Python腳本GitHub/語雀自動更新

由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址

GitHub: Karobben
Blog:Karobben
BiliBili:史上最不正經的生物狗