量化投資與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()
案例四:柱狀圖與餅狀圖 (bar、pie)
# 柱狀圖
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()
案例五:繪制橫向柱狀圖 barh
import matplotlib.pyplot as plt
import numpy as np
x = [5, 8, 13, 21]
y = ['a', 'b', 'c', 'd']
plt.barh(x,y)
案例六:繪制直方圖 hist
是一個特殊的柱狀圖,又叫做密度圖
- plt.hist()的參數
+ bins
可以是一個bin數量的整數值,也可以是表示bin的一個序列。預設值為10
+ normed
如果值為True,直方圖的值将進行歸一化處理,形成機率密度,預設值為False
+ color
指定直方圖的顔色。可以是單一顔色值或顔色的序列。如果指定了多個資料集合,例如DataFrame對象,顔色序列将會設定為相同的順序。如果未指定,将會使用一個預設的線條顔色
+ orientation
通過設定orientation為horizontal建立水準直方圖。預設值為vertical、
data = [1,2,3,1,2,3,4,6,7,4,7,5,3,5,2,3]
plt.hist(data,bins=20)
案例七:散點圖 scatter
因變量随自變量而變化的大緻趨勢
import numpy as np
x = np.array([4,5,6,1,8,4])
y = x **3
plt.scatter(x,y)
案例:繪制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()
Matplotlib 線點顔色參數,來自源碼
============= ===============================
character description
============= ===============================
``'.'`` point marker
``','`` pixel marker
``'o'`` circle marker
``'v'`` triangle_down marker
``'^'`` triangle_up marker
``'<'`` triangle_left marker
``'>'`` triangle_right marker
``'1'`` tri_down marker
``'2'`` tri_up marker
``'3'`` tri_left marker
``'4'`` tri_right marker
``'s'`` square marker
``'p'`` pentagon marker
``'*'`` star marker
``'h'`` hexagon1 marker
``'H'`` hexagon2 marker
``'+'`` plus marker
``'x'`` x marker
``'D'`` diamond marker
``'d'`` thin_diamond marker
``'|'`` vline marker
``'_'`` hline marker
**Line Styles**
``'-'`` solid line style
``'--'`` dashed line style
``'-.'`` dash-dot line style
``':'`` dotted line style
Example format strings::
'b' # blue markers with default shape
'or' # red circles
'-g' # green solid line
'--' # dashed line with default color
'^k:' # black triangle_up markers connected by a dotted line
**Colors**
The supported color abbreviations are the single letter codes
character color
``'b'`` blue
``'g'`` green
``'r'`` red
``'c'`` cyan
``'m'`` magenta
``'y'`` yellow
``'k'`` black
``'w'`` white