0


Python绘图

1.二维绘图

a. 一维数据集

用 Numpy ndarray 作为数据传入 ply

  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(10)
  6. print "y = %s"% y
  7. x = range(len(y))
  8. print "x=%s"% x
  9. plt.plot(y)
  10. plt.show()

2.操纵坐标轴和增加网格及标签的函数

  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(10)
  6. plt.plot(y.cumsum())
  7. plt.grid(True) ##增加格点
  8. plt.axis('tight') # 坐标轴适应数据量 axis 设置坐标轴
  9. plt.show()

3.plt.xlim 和 plt.ylim 设置每个坐标轴的最小值和最大值

  1. #!/etc/bin/python
  2. #coding=utf-8
  3. import numpy as np
  4. import matplotlib as mpl
  5. import matplotlib.pyplot as plt
  6. np.random.seed(1000)
  7. y = np.random.standard_normal(20)
  8. plt.plot(y.cumsum())
  9. plt.grid(True) ##增加格点
  10. plt.xlim(-1,20)
  11. plt.ylim(np.min(y.cumsum())- 1, np.max(y.cumsum()) + 1)
  12. plt.show()

  1. 添加标题和标签 plt.title, plt.xlabe, plt.ylabel 离散点, 线
  1. #!/etc/bin/python
  2. #coding=utf-8
  3. import numpy as np
  4. import matplotlib as mpl
  5. import matplotlib.pyplot as plt
  6. np.random.seed(1000)
  7. y = np.random.standard_normal(20)
  8. plt.figure(figsize=(7,4)) #画布大小
  9. plt.plot(y.cumsum(),'b',lw = 1.5) # 蓝色的线
  10. plt.plot(y.cumsum(),'ro') #离散的点
  11. plt.grid(True)
  12. plt.axis('tight')
  13. plt.xlabel('index')
  14. plt.ylabel('value')
  15. plt.title('A simple Plot')
  16. plt.show()

b. 二维数据集

  1. np.random.seed(2000)
  2. y = np.random.standard_normal((10, 2)).cumsum(axis=0) #10行2列 在这个数组上调用cumsum 计算赝本数据在0轴(即第一维)上的总和
  3. print y

1.两个数据集绘图

  1. #!/etc/bin/python
  2. #coding=utf-8
  3. import numpy as np
  4. import matplotlib as mpl
  5. import matplotlib.pyplot as plt
  6. np.random.seed(2000)
  7. y = np.random.standard_normal((10, 2))
  8. plt.figure(figsize=(7,5))
  9. plt.plot(y, lw = 1.5)
  10. plt.plot(y, 'ro')
  11. plt.grid(True)
  12. plt.axis('tight')
  13. plt.xlabel('index')
  14. plt.ylabel('value')
  15. plt.title('A simple plot')
  16. plt.show()

2.添加图例 plt.legend(loc = 0)

  1. #!/etc/bin/python
  2. #coding=utf-8
  3. import numpy as np
  4. import matplotlib as mpl
  5. import matplotlib.pyplot as plt
  6. np.random.seed(2000)
  7. y = np.random.standard_normal((10, 2))
  8. plt.figure(figsize=(7,5))
  9. plt.plot(y[:,0], lw = 1.5,label = '1st')
  10. plt.plot(y[:,1], lw = 1.5, label = '2st')
  11. plt.plot(y, 'ro')
  12. plt.grid(True)
  13. plt.legend(loc = 0) #图例位置自动
  14. plt.axis('tight')
  15. plt.xlabel('index')
  16. plt.ylabel('value')
  17. plt.title('A simple plot')
  18. plt.show()

3.使用2个 Y轴(左右)fig, ax1 = plt.subplots() ax2 = ax1.twinx()

  1. #!/etc/bin/python
  2. #coding=utf-8
  3. import numpy as np
  4. import matplotlib as mpl
  5. import matplotlib.pyplot as plt
  6. np.random.seed(2000)
  7. y = np.random.standard_normal((10, 2))
  8. fig, ax1 = plt.subplots() # 关键代码1 plt first data set using first (left) axis
  9. plt.plot(y[:,0], lw = 1.5,label = '1st')
  10. plt.plot(y[:,0], 'ro')
  11. plt.grid(True)
  12. plt.legend(loc = 0) #图例位置自动
  13. plt.axis('tight')
  14. plt.xlabel('index')
  15. plt.ylabel('value')
  16. plt.title('A simple plot')
  17. ax2 = ax1.twinx() #关键代码2 plt second data set using second(right) axis
  18. plt.plot(y[:,1],'g', lw = 1.5, label = '2nd')
  19. plt.plot(y[:,1], 'ro')
  20. plt.legend(loc = 0)
  21. plt.ylabel('value 2nd')
  22. plt.show()

4.使用两个子图(上下,左右)plt.subplot(211)

通过使用 plt.subplots 函数,可以直接访问底层绘图对象,例如可以用它生成和第一个子图共享 x 轴的第二个子图.

  1. #!/etc/bin/python
  2. #coding=utf-8
  3. import numpy as np
  4. import matplotlib as mpl
  5. import matplotlib.pyplot as plt
  6. np.random.seed(2000)
  7. y = np.random.standard_normal((10, 2))
  8. plt.figure(figsize=(7,5))
  9. plt.subplot(211) #两行一列,第一个图
  10. plt.plot(y[:,0], lw = 1.5,label = '1st')
  11. plt.plot(y[:,0], 'ro')
  12. plt.grid(True)
  13. plt.legend(loc = 0) #图例位置自动
  14. plt.axis('tight')
  15. plt.ylabel('value')
  16. plt.title('A simple plot')
  17. plt.subplot(212) #两行一列.第二个图
  18. plt.plot(y[:,1],'g', lw = 1.5, label = '2nd')
  19. plt.plot(y[:,1], 'ro')
  20. plt.grid(True)
  21. plt.legend(loc = 0)
  22. plt.xlabel('index')
  23. plt.ylabel('value 2nd')
  24. plt.axis('tight')
  25. plt.show()

5.左右子图

有时候,选择两个不同的图标类型来可视化数据可能是必要的或者是理想的.利用子图方法:

  1. #!/etc/bin/python
  2. #coding=utf-8
  3. import numpy as np
  4. import matplotlib as mpl
  5. import matplotlib.pyplot as plt
  6. np.random.seed(2000)
  7. y = np.random.standard_normal((10, 2))
  8. plt.figure(figsize=(10,5))
  9. plt.subplot(121) #两行一列,第一个图
  10. plt.plot(y[:,0], lw = 1.5,label = '1st')
  11. plt.plot(y[:,0], 'ro')
  12. plt.grid(True)
  13. plt.legend(loc = 0) #图例位置自动
  14. plt.axis('tight')
  15. plt.xlabel('index')
  16. plt.ylabel('value')
  17. plt.title('1st Data Set')
  18. plt.subplot(122)
  19. plt.bar(np.arange(len(y)), y[:,1],width=0.5, color='g',label = '2nc')
  20. plt.grid(True)
  21. plt.legend(loc=0)
  22. plt.axis('tight')
  23. plt.xlabel('index')
  24. plt.title('2nd Data Set')
  25. plt.show()

c.其他绘图样式,散点图,直方图等

1.散点图 scatter

  1. #!/etc/bin/python
  2. #coding=utf-8
  3. import numpy as np
  4. import matplotlib as mpl
  5. import matplotlib.pyplot as plt
  6. np.random.seed(2000)
  7. y = np.random.standard_normal((1000, 2))
  8. plt.figure(figsize=(7,5))
  9. plt.scatter(y[:,0],y[:,1],marker='o')
  10. plt.grid(True)
  11. plt.xlabel('1st')
  12. plt.ylabel('2nd')
  13. plt.title('Scatter Plot')
  14. plt.show()

2.直方图 plt.hist

  1. #!/etc/bin/python
  2. #coding=utf-8
  3. import numpy as np
  4. import matplotlib as mpl
  5. import matplotlib.pyplot as plt
  6. np.random.seed(2000)
  7. y = np.random.standard_normal((1000, 2))
  8. plt.figure(figsize=(7,5))
  9. plt.hist(y,label=['1st','2nd'],bins=25)
  10. plt.grid(True)
  11. plt.xlabel('value')
  12. plt.ylabel('frequency')
  13. plt.title('Histogram')
  14. plt.show()

3.直方图 同一个图中堆叠

  1. #!/etc/bin/python
  2. #coding=utf-8
  3. import numpy as np
  4. import matplotlib as mpl
  5. import matplotlib.pyplot as plt
  6. np.random.seed(2000)
  7. y = np.random.standard_normal((1000, 2))
  8. plt.figure(figsize=(7,5))
  9. plt.hist(y,label=['1st','2nd'],color=['b','g'],stacked=True,bins=20)
  10. plt.grid(True)
  11. plt.xlabel('value')
  12. plt.ylabel('frequency')
  13. plt.title('Histogram')
  14. plt.show()

4.箱型图 boxplot

  1. #!/etc/bin/python
  2. #coding=utf-8
  3. import numpy as np
  4. import matplotlib as mpl
  5. import matplotlib.pyplot as plt
  6. np.random.seed(2000)
  7. y = np.random.standard_normal((1000, 2))
  8. fig, ax = plt.subplots(figsize=(7,4))
  9. plt.boxplot(y)
  10. plt.grid(True)
  11. plt.setp(ax,xticklabels=['1st' , '2nd'])
  12. plt.xlabel('value')
  13. plt.ylabel('frequency')
  14. plt.title('Histogram')
  15. plt.show()

5.绘制函数

  1. from matplotlib.patches import Polygon
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. #1. 定义积分函数
  5. def func(x):
  6. return 0.5 * np.exp(x)+1
  7. #2.定义积分区间
  8. a,b = 0.5, 1.5
  9. x = np.linspace(0, 2 )
  10. y = func(x)
  11. #3.绘制函数图形
  12. fig, ax = plt.subplots(figsize=(7,5))
  13. plt.plot(x,y, 'b',linewidth=2)
  14. plt.ylim(ymin=0)
  15. #4.核心, 我们使用Polygon函数生成阴影部分,表示积分面积:
  16. Ix = np.linspace(a,b)
  17. Iy = func(Ix)
  18. verts = [(a,0)] + list(zip(Ix, Iy))+[(b,0)]
  19. poly = Polygon(verts,facecolor='0.7',edgecolor = '0.5')
  20. ax.add_patch(poly)
  21. #5.用plt.text和plt.figtext在图表上添加数学公式和一些坐标轴标签。
  22. plt.text(0.5 *(a+b),1,r"$\int_a^b f(x)\mathrm{d}x$", horizontalalignment ='center',fontsize=20)
  23. plt.figtext(0.9, 0.075,'$x$')
  24. plt.figtext(0.075, 0.9, '$f(x)$')
  25. #6. 分别设置x,y刻度标签的位置。
  26. ax.set_xticks((a,b))
  27. ax.set_xticklabels(('$a$','$b$'))
  28. ax.set_yticks([func(a),func(b)])
  29. ax.set_yticklabels(('$f(a)$','$f(b)$'))
  30. plt.grid(True)

2.金融学图表 matplotlib.finance

1.烛柱图 candlestick

  1. #!/etc/bin/python
  2. #coding=utf-8
  3. import matplotlib.pyplot as plt
  4. import matplotlib.finance as mpf
  5. start = (2014, 5,1)
  6. end = (2014, 7,1)
  7. quotes = mpf.quotes_historical_yahoo('^GDAXI',start,end)
  8. # print quotes[:2]
  9. fig, ax = plt.subplots(figsize=(8,5))
  10. fig.subplots_adjust(bottom = 0.2)
  11. mpf.candlestick(ax, quotes, width=0.6, colorup='b',colordown='r')
  12. plt.grid(True)
  13. ax.xaxis_date() #x轴上的日期
  14. ax.autoscale_view()
  15. plt.setp(plt.gca().get_xticklabels(),rotation=30) #日期倾斜
  16. plt.show()

  1. plot_day_summary

该函数提供了一个相当类似的图标类型,使用方法和 candlestick 函数相同,使用类似的参数. 这里开盘价和收盘价不是由彩色矩形表示,而是由两条短水平线表示.

  1. #!/etc/bin/python
  2. #coding=utf-8
  3. import matplotlib.pyplot as plt
  4. import matplotlib.finance as mpf
  5. start = (2014, 5,1)
  6. end = (2014, 7,1)
  7. quotes = mpf.quotes_historical_yahoo('^GDAXI',start,end)
  8. # print quotes[:2]
  9. fig, ax = plt.subplots(figsize=(8,5))
  10. fig.subplots_adjust(bottom = 0.2)
  11. mpf.plot_day_summary(ax, quotes, colorup='b',colordown='r')
  12. plt.grid(True)
  13. ax.xaxis_date() #x轴上的日期
  14. ax.autoscale_view()
  15. plt.setp(plt.gca().get_xticklabels(),rotation=30) #日期倾斜
  16. plt.show()

3.股价数据和成交量

  1. #!/etc/bin/python
  2. #coding=utf-8
  3. import matplotlib.pyplot as plt
  4. import numpy as np
  5. import matplotlib.finance as mpf
  6. start = (2014, 5,1)
  7. end = (2014, 7,1)
  8. quotes = mpf.quotes_historical_yahoo('^GDAXI',start,end)
  9. # print quotes[:2]
  10. quotes = np.array(quotes)
  11. fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(8,6))
  12. mpf.candlestick(ax1, quotes, width=0.6,colorup='b',colordown='r')
  13. ax1.set_title('Yahoo Inc.')
  14. ax1.set_ylabel('index level')
  15. ax1.grid(True)
  16. ax1.xaxis_date()
  17. plt.bar(quotes[:,0] - 0.25, quotes[:, 5], width=0.5)
  18. ax2.set_ylabel('volume')
  19. ax2.grid(True)
  20. ax2.autoscale_view()
  21. plt.setp(plt.gca().get_xticklabels(),rotation=30)
  22. plt.show()

3.3D 绘图

  1. #!/etc/bin/python
  2. #coding=utf-8
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. stike = np.linspace(50, 150, 24)
  6. ttm = np.linspace(0.5, 2.5, 24)
  7. stike, ttm = np.meshgrid(stike, ttm)
  8. print stike[:2]
  9. iv = (stike - 100) ** 2 / (100 * stike) /ttm
  10. from mpl_toolkits.mplot3d import Axes3D
  11. fig = plt.figure(figsize=(9,6))
  12. ax = fig.gca(projection='3d')
  13. surf = ax.plot_surface(stike, ttm, iv, rstride=2, cstride=2, cmap=plt.cm.coolwarm, linewidth=0.5, antialiased=True)
  14. ax.set_xlabel('strike')
  15. ax.set_ylabel('time-to-maturity')
  16. ax.set_zlabel('implied volatility')
  17. plt.show()

标签: python numpy matplotlib

本文转载自: https://blog.csdn.net/m0_59485658/article/details/129371433
版权归原作者 代码输入中... 所有, 如有侵权,请联系我们删除。

“Python绘图”的评论:

还没有评论