python_matplotlib使用

目录

1. 绘制多项式函数

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

3. 直方图

4. 对数坐标图

5. 散点图

6. 着色

7. 图例和注释


1. 绘制多项式函数

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

plt.plot(x,y)
plt.xlabel('x')
plt.ylabel('y')

 

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

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

 

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

 

3. 直方图

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

 

4. 对数坐标图

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

 

5. 散点图

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

 

6. 着色

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

 

7. 图例和注释

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

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值