Day 79 量化投资与Python——Matplotlib

量化投资与Python——Matplotlib

简介

案例

Matplotlib官网

案例一:常用函数

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

x = np.linspace(-5, 5, 20)
y1 = x
y2 = x ** 2
y3 = 3 * x ** 3 + 5 * x ** 2 + 2 * x + 1
plt.plot(x, y1, 'h-r', label='y=x')
plt.plot(x, y2, '*-c', label='y=x**2')
plt.plot(x, y3, label='y=3x**3+5x**2+2x+1')
plt.title('折线图')
plt.xlabel('x轴')
plt.ylabel('y轴')
# plt.xlim(0, 10)  # x轴的范围
# plt.ylim(0, 10)  # x轴的范围
# plt.xticks(np.arange(0, 10, 3))  # 刻度、步长
# plt.yticks(np.arange(0, 10, 3))  # 刻度、步长
plt.legend()  # 设置曲线图例说明

plt.show()

案例二:画布

x = np.linspace(-5, 5, 20)
y1 = x
y2 = x ** 2
y3 = 3 * x ** 3 + 5 * x ** 2 + 2 * x + 1
fig = plt.figure()
ax1 = fig.add_subplot(2, 2, 1)
ax1.plot(x, y2, 'o-r')
fig.show()

ax2 = fig.add_subplot(2, 2, 2)
ax2.plot(x, y1, 'o-r', label='y=x')
fig.show()

ax3 = fig.add_subplot(2, 2, 3)
ax3.plot(x, y3, 'o-r', label='y=x')
fig.show()

案例四:柱状图与饼状图

# 柱状图
data = [5, 8, 13, 21]
label = ['a', 'b', 'c', 'd']
plt.bar(np.arange(len(data)), data, align='center', color='red', width=0.3)  # 默认 align='center' width=0.8
plt.xticks(np.arange(len(data)), labels=label)
plt.show()

# 饼状图
data = [5, 8, 13, 21]
label = ['a', 'b', 'c', 'd']
plt.pie(data,labels=label,autopct='%.2f%%',explode=[0,0,0.1,0])# .2 表示保留两位小数
# plt.axis('equal') # 是图竖起来
plt.show()

案例五:绘制K线图

# mpl_finance 中有许多绘制金融相关的函数接口
# 绘制K线图:mpl_finance.candlestick_ochl 函数
import mpl_finance as fin
import pandas as pd
from matplotlib.dates import date2num

df = pd.read_csv('./601318.csv', parse_dates=['date'], index_col=['date'])[['open', 'close', 'high', 'low']]
df['time'] = date2num(df.index.to_pydatetime())
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
arr = df[['time', 'open', 'close', 'high', 'low']].values
fin.candlestick_ochl(ax, arr)
plt.grid()
fig.show()

 

 

 

猜你喜欢

转载自www.cnblogs.com/ysging/p/13202561.html
79