Day 79 量化投資與Python——Matplotlib
阿新 • • 發佈:2020-06-28
量化投資與Python——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()