当前位置:   article > 正文

python_matplotlib使用_import matplotlib.pyplot as plt

import matplotlib.pyplot as plt

目录

1. 绘制多项式函数

2. 绘制多项式函数及其导函数

3. 直方图

4. 对数坐标图

5. 散点图

6. 着色

7. 图例和注释


1. 绘制多项式函数

  1. import pandas as pd
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. %matplotlib inline
  5. # 1. 绘制多项式函数
  6. # 以自然数序列作为多项式的系数,使用poly1d函数创建多项式
  7. func = np.poly1d(np.array([1,2,3,4]).astype(float))
  8. x = np.linspace(-10,10,30)
  9. y = func(x)
  10. plt.plot(x,y)
  11. plt.xlabel('x')
  12. plt.ylabel('y')

 

2. 绘制多项式函数及其导函数

  1. # 2. 绘制多项式函数及其导函数
  2. func = np.poly1d(np.array([1,2,3,4]).astype(float))
  3. func1 = func.deriv(m=1)
  4. x = np.linspace(-10,10,30)
  5. y = func(x)
  6. y1 = func1(x)
  7. plt.plot(x,y,'ro',x,y1,'g--')
  8. plt.xlabel('x')
  9. plt.ylabel('y')

 

  1. func2 = func.deriv(m=2)
  2. y2 = func2(x)
  3. '''
  4. 使用subplot函数创建子图。该函数第一个参数是子图的行数,第二个参数是子图的列数,第三个参数是一个从1开始的序号。另一种方式是将这
  5. 3个参数结合成一个数字,如311
  6. '''
  7. plt.subplot(311)
  8. plt.plot(x,y,'r-')
  9. plt.title('Polynomial')
  10. plt.subplot(312)
  11. plt.plot(x,y1,'b^')
  12. plt.title('First Drivative')
  13. plt.subplot(313)
  14. plt.plot(x,y2,'go')
  15. plt.title('Second Drivative')
  16. plt.xlabel('x')
  17. plt.ylabel('y')

 

3. 直方图

  1. # 3. 直方图
  2. df = pd.read_csv('AAPL.csv',encoding='utf-8')
  3. df = df.iloc[-252:]
  4. close_s = np.array(df['Close'])
  5. plt.hist(close_s,int(np.sqrt(len(close_s))))

 

4. 对数坐标图

  1. # 4. 对数坐标图
  2. '''
  3. 当数据的变化范围很大时,对数坐标图很有用
  4. Matplotlib中有 semilogx对x轴取对数,semilogy对y轴取对数、loglog同时对x轴和y轴取对数
  5. '''
  6. volume = df['Volume']
  7. plt.subplot(211)
  8. plt.plot(volume)
  9. plt.title('Normal Volume')
  10. plt.subplot(212)
  11. plt.semilogy(volume)
  12. plt.title('Log Volume')
  13. plt.subplots_adjust(wspace=0.5,hspace=0.5)

 

5. 散点图

  1. # 5. 散点图
  2. # 绘制股票收益率和成交量变化散点图
  3. df = pd.read_csv('AAPL.csv',encoding='utf-8')
  4. df['ret'] = (df['Close']-df['Close'].shift(1))/df['Close'].shift(1)
  5. df['volchange'] = (df['Volume']-df['Volume'].shift(1))/df['Volume'].shift(1)
  6. df = df.iloc[-252:]
  7. fig = plt.figure()
  8. ax = fig.add_subplot(111)
  9. ax.scatter(df['ret'],df['volchange'],c=df['ret']*100,s=df['volchange']*100,alpha=0.5)
  10. ax.set_title('Close and volume returns')
  11. ax.grid(True)

 

6. 着色

  1. # 6. 着色
  2. '''
  3. 题目:对股票曲线图进行着色,并将低于均值和高于均值的收盘价填充为不同颜色。
  4. '''
  5. fig = plt.figure()
  6. ax = fig.add_subplot(111)
  7. x = range(len(df))
  8. ax.plot(x,df['Close'])
  9. plt.fill_between(x,df['Close'].min(),df['Close'],where=df['Close']>df['Close'].mean(),facecolor='green',alpha=0.4)
  10. plt.fill_between(x,df['Close'].min(),df['Close'],where=df['Close']<df['Close'].mean(),facecolor='red',alpha=0.4)

 

7. 图例和注释

  1. # 7. 图例和注释
  2. # 计算并绘制指数移动平均线
  3. # 分别使用 9 12 15 作为周期数计算和绘制指数移动平均线
  4. df = df.iloc[-100:]
  5. fig = plt.figure()
  6. ax = fig.add_subplot(111)
  7. df['count'] = range(len(df))
  8. x = df['count']
  9. close = df['Close']
  10. emas= []
  11. for i in range(9,18,3):
  12. weights = np.exp(np.linspace(-1.,0.,i))
  13. weights /= weights.sum()
  14. ema = np.convolve(weights,close)[i-1:-i+1]
  15. idx = (i-6)/3
  16. ax.plot(x[i-1:],ema,lw=idx,label='EMA(%s)'%(i))
  17. data = np.column_stack((x[i-1:],ema))
  18. emas.append(np.rec.fromrecords(data,names=['dates','ema']))
  19. first = emas[0]['ema'].flatten()
  20. second = emas[1]['ema'].flatten()
  21. bools = np.abs(first[-len(second):]-second)/second<0.0001
  22. xpoints = np.compress(bools,emas[1])
  23. for xpoint in xpoints:
  24. ax.annotate('x',xy=xpoint,textcoords='offset points',xytext=(-50,30),arrowprops=dict(arrowstyle='->'))
  25. leg = ax.legend(loc='best',fancybox=True)
  26. leg.get_frame().set_alpha(0.5)

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/166949
推荐阅读
相关标签
  

闽ICP备14008679号