按照給定的x和y值繪圖
import matplotlib as mplimport matplotlib.pyplot as plt%matplotlib inline # 如果是在控制臺(tái)上執(zhí)行代碼,這行如果報(bào)錯(cuò),下面的圖片顯示一張,關(guān)閉后再執(zhí)行下一張的顯示,不然都會(huì)畫到一張圖上np.random.seed(1000)# 生成20個(gè)標(biāo)準(zhǔn)正態(tài)分布(偽)隨機(jī)數(shù), 保存在一個(gè)NumPy ndarray中y = np.random.standard_normal(20)x = range(len(y))plt.plot(x, y)plt.title('5-1 按照給定的x和y值繪圖')
按照給定的一維數(shù)組和附加方法繪圖
# 按照給定的一維數(shù)組和附加方法繪圖plt.plot(y)plt.title('5-2 按照一維數(shù)組給出的數(shù)據(jù)繪圖')
按照給定的一維數(shù)組和附加方法繪圖
# 按照給定的一維數(shù)組和附加方法繪圖plt.plot(y.cumsum())plt.title('5-3 按照給定的一維數(shù)組和附加方法繪圖')
帶有網(wǎng)絡(luò)和緊湊坐標(biāo)軸的圖表
# 帶有網(wǎng)絡(luò)和緊湊坐標(biāo)軸的圖表plt.plot(y.cumsum())plt.grid(True)plt.axis('tight')plt.title('5-4 帶有網(wǎng)絡(luò)和緊湊坐標(biāo)軸的圖表')
參數(shù) | 描述 |
---|---|
Empty | 返回當(dāng)前坐標(biāo)軸限值 |
off | 關(guān)閉坐標(biāo)軸和標(biāo)簽 |
equat | 使用等刻度 |
scaled | 通過尺寸變化平衡度量 |
tight | 所有數(shù)據(jù)可見(縮小限值) |
image | 是所有數(shù)據(jù)可見(使用數(shù)據(jù)限值) |
[xmin,xmax,ymin,ymax] | 將設(shè)置限值為給定的一組值 |
使用自定義坐標(biāo)軸限值繪制圖表
# 使用自定義坐標(biāo)軸限值繪制圖表plt.plot(y.cumsum())plt.grid(True)plt.xlim(-1, 20)plt.ylim(np.min(y.cumsum()) - 1, np.max(y.cumsum()) + 1)plt.title('5-5 使用自定義坐標(biāo)軸限值繪制圖表')
# 帶有典型標(biāo)簽的圖表plt.figure(figsize=(7, 4))# the figsize parameter defines the size of the figure in (width,height)plt.plot(y.cumsum(),'b',lw=1.5)plt.plot(y.cumsum(),'ro')plt.grid(True)plt.axis('tight')plt.xlabel('index')plt.ylabel('value')plt.title('A Simple Plot')
標(biāo)準(zhǔn)顏色縮寫
字符 | 顏色 |
---|---|
b | 藍(lán) |
g | 綠 |
r | 紅 |
c | 青 |
m | 品紅 |
y | 黃 |
k | 黑 |
w | 白 |
標(biāo)準(zhǔn)樣式字符
字符 | 象征 |
---|---|
- | 實(shí)現(xiàn)樣式 |
– | 短劃線樣式 |
-. | 點(diǎn)實(shí)線樣式 |
: | 虛線樣式 |
. | 點(diǎn)標(biāo)記 |
, | 像素標(biāo)記 |
o | 圓標(biāo)記 |
v | 向下三角形標(biāo)記 |
^ | 向上三角形標(biāo)記 |
< | 向左三角形標(biāo)記 |
> | 向右三角形標(biāo)記 |
1 | Tri_down標(biāo)記 |
2 | Tri_up標(biāo)記 |
3 | Tri_left標(biāo)記 |
4 | Tri_right標(biāo)記 |
s | 方形標(biāo)記 |
P | 五邊形標(biāo)記 |
* | 星號(hào) |
h | 六角形標(biāo)記1 |
H | 六角形標(biāo)記2 |
+ | 加好 |
x | X標(biāo)記 |
D | 菱形標(biāo)記 |
d | 細(xì)菱形標(biāo)記 |
| | 垂直標(biāo)記 |
用兩個(gè)數(shù)據(jù)集繪制圖表
# 用兩個(gè)數(shù)據(jù)集繪制圖表np.random.seed(2000)y = np.random.standard_normal((20, 2)).cumsum(axis=0)plt.figure(figsize=(7, 4))plt.plot(y, lw=1.5)plt.plot(y, 'ro')plt.grid(True)plt.axis('tight')plt.xlabel('index')plt.ylabel('value')plt.title('A Simple Plot')
# 帶有數(shù)據(jù)集的圖表plt.figure(figsize=(7, 4))plt.plot(y[:, 0], lw=1.5, label='1st')plt.plot(y[:, 1], lw=1.5, label='2nd')plt.grid(True)plt.legend(loc=0)plt.axis('tight')plt.xlabel('index')plt.ylabel('value')plt.title('A Simple Plot')
位置選項(xiàng) | 描述 |
---|---|
空白 | 自動(dòng) |
0 | 最佳 |
1 | 右上 |
2 | 左上 |
3 | 左下 |
4 | 右下 |
5 | 右 |
6 | 中左 |
7 | 中右 |
8 | 中下 |
9 | 中上 |
10 | 中 |
包含兩個(gè)數(shù)據(jù)集、 兩個(gè)y軸的圖表
# 包含兩個(gè)數(shù)據(jù)集、 兩個(gè)y軸的圖表y[:, 0] = y[:, 0] * 10fig, ax1 = plt.subplots()plt.plot(y[:, 0], 'b', lw=1.5, label='1st')plt.plot(y[:, 0], 'ro')plt.grid(True)plt.legend(loc=8)plt.axis('tight')plt.xlabel('index')plt.ylabel('value 1st')plt.title('A Simple Plot')ax2 = ax1.twinx()plt.plot(y[:, 1], 'g', lw=1.5, label='2nd')plt.legend(loc=0)plt.ylabel('value 2nd')
帶有兩個(gè)子圖的圖表
# 帶有兩個(gè)子圖的圖表plt.figure(figsize=(7, 5))plt.subplot(211)plt.plot(y[:, 0], 'b', lw=1.5, label='1st')plt.plot(y[:, 0], 'ro')plt.grid(True)plt.legend(loc=0)plt.axis('tight')plt.ylabel('value')plt.title('A Simple Plot')plt.subplot(212)plt.plot(y[:, 0], 'g', lw=1.5, label='2nd')plt.plot(y[:, 0], 'ro')plt.grid(True)plt.legend(loc=0)plt.axis('tight')plt.xlabel('index')plt.ylabel('value')
組合線、點(diǎn)子圖和柱狀子圖
# 組合線、點(diǎn)子圖和柱狀子圖plt.figure(figsize=(9, 4))plt.subplot(121)plt.plot(y[:, 0], lw=1.5, label='1st')plt.plot(y[:, 0], 'ro')plt.grid(True)plt.legend(loc=0)plt.axis('tight')plt.xlabel('index')plt.ylabel('value')plt.title('1st Data Set')plt.subplot(122)plt.bar(np.arange(len(y)), y[:, 1], width=0.5, color='g', label='2nd')plt.grid(True)plt.legend(loc=0)plt.axis('tight')plt.xlabel('index')plt.title('2nd Data Set')
通過plot函數(shù)繪制散點(diǎn)圖
# 通過plot函數(shù)繪制散點(diǎn)圖y = np.random.standard_normal((1000, 2))plt.figure(figsize=(7, 5))plt.plot(y[:, 0], y[:, 1], 'ro')plt.grid(True)plt.xlabel('1st')plt.ylabel('2nd')plt.title('Scatter Plot')
通過scatter函數(shù)繪制散點(diǎn)圖
# 通過scatter函數(shù)繪制散點(diǎn)圖plt.figure(figsize=(7, 5))plt.scatter(y[:, 0], y[:, 1], marker='o')plt.grid(True)plt.xlabel('1st')plt.ylabel('2nd')plt.title('Scatter Plot')
# 具備第三維的散點(diǎn)圖c = np.random.randint(0, 10, len(y))plt.figure(figsize=(7, 5))plt.scatter(y[:, 0], y[:, 1], c=c, marker='o')plt.colorbar()plt.grid(True)plt.xlabel('1st')plt.ylabel('2nd')plt.title('Scatter Plot')
# 兩個(gè)數(shù)據(jù)集的直方圖plt.figure(figsize=(7, 5))plt.hist(y, label=['1st', '2nd'], bins=25)plt.grid(True)plt.legend(loc=0)plt.xlabel('value')plt.ylabel('frequency')plt.title('Histogram')
plt.hist所支持的參數(shù):
plt.hist(x, bins=None, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype=’bar’, align=’mid’, orientation=’vertical’, rwidth=None, log=False, color=None, label=None, stacked=False, hold=None, data=None, **kwargs)
plt.hist參數(shù)
參數(shù) | 描述 |
---|---|
x | 列表對(duì)象,ndarray對(duì)象 |
bins | 數(shù)據(jù)組(bin)數(shù) |
range | 數(shù)據(jù)組的上界和下界 |
normed | 規(guī)范化為整數(shù) |
weights | x軸上每個(gè)值的權(quán)重 |
cumulative | 每個(gè)數(shù)據(jù)組包含較低組別的計(jì)數(shù) |
histtype | 選項(xiàng)(字符串): bar, barstacked, step, stepfilled |
align | 選項(xiàng)(字符串): lef, mid, right |
orientation | 選項(xiàng)(字符串): horizontal, vertical |
rwidth | 條塊的相對(duì)寬度 |
log | 對(duì)數(shù)刻度 |
color | 每個(gè)數(shù)據(jù)集的顏色(類似數(shù)組) |
label | 標(biāo)簽所用的字符席或者字符串序列 |
stacked | 堆疊多個(gè)數(shù)據(jù)集 |
兩個(gè)數(shù)據(jù)集堆疊的直方圖
# 兩個(gè)數(shù)據(jù)集堆疊的直方圖plt.figure(figsize=(7, 4))plt.hist(y, label=['1st', '2nd'], color=['b', 'g'], stacked=True, bins=20)plt.grid(True)plt.legend(loc=0)plt.xlabel('value')plt.ylabel('frequency')plt.title('Histogram')
兩個(gè)數(shù)據(jù)集的箱形圖
# 兩個(gè)數(shù)據(jù)集的箱形圖fig, ax = plt.subplots(figsize=(7, 4))plt.boxplot(y)plt.grid(True)plt.setp(ax, xticklabels=['1st', '2nd'])plt.xlabel('data set')plt.ylabel('value')plt.title('Boxplot')
指數(shù)函數(shù)、積分面積和LaTeX標(biāo)簽
# 指數(shù)函數(shù)、積分面積和LaTeX標(biāo)簽from matplotlib.patches import Polygondef func(x): return 0.5 * np.exp(x) + 1a, b = 0.5, 1.5x = np.linspace(0, 2)y = func(x)fig, ax = plt.subplots(figsize=(7, 5))plt.plot(x, y, 'b', linewidth=2)plt.ylim(ymin=0)Ix = np.linspace(a, b)Iy = func(Ix)verts = [(a, 0)] + list(zip(Ix, Iy)) + [(b, 0)]poly = Polygon(verts, facecolor='0.7', edgecolor='0.5')ax.add_patch(poly)plt.text(0.5 * (a + b), 1, r"$\int_a^b f(x)\mathrmmoiyehiwx$", horizontalalignment='center', fontsize=20)plt.figtext(0.9, 0.075, '$x$')plt.figtext(0.075, 0.9, '$x$')ax.set_xticks((a, b))ax.set_xticklabels(('$a$', '$b$'))ax.set_yticks([func(a), func(b)])ax.set_yticklabels(('$f(a)$', '$f(b)$'))plt.grid(True)
金融數(shù)據(jù)的蠟燭圖
import matplotlib.finance as mpf# start = (2014, 5, 1)# end = (2014, 6, 30)# quotes = mpf._quotes_historical_yahoo('GDAXI', start, end)# 由于偉大的墻,調(diào)取不到國(guó)外的數(shù)據(jù),這里用tushare獲取600118中國(guó)衛(wèi)星的數(shù)據(jù)import tushare as tsimport datetimefrom matplotlib.pylab import date2numstart = '2018-05-01'end = '2018-06-30'k_d = ts.get_k_data('600118', start, end, ktype='D')k_d.head()k_d.date = k_d.date.map(lambda x: date2num(datetime.datetime.strptime(x, '%Y-%m-%d')))quotes = k_d.valuesfig, ax = plt.subplots(figsize=(8, 5))fig.subplots_adjust(bottom=0.2)mpf.candlestick_ochl(ax, quotes, width=0.6, colorup='r', colordown='g', alpha=0.8)plt.grid(True)ax.xaxis_date()# dates on the x-axisax.autoscale_view()plt.setp(plt.gca().get_xticklabels(), rotation=30)
k_d.head()輸入的結(jié)果:
date | open | close | high | low | volume | code | |
---|---|---|---|---|---|---|---|
77 | 2018-05-02 | 23.05 | 22.45 | 23.10 | 22.25 | 90673.0 | 600118 |
78 | 2018-05-03 | 22.30 | 22.52 | 22.58 | 21.71 | 78948.0 | 600118 |
79 | 2018-05-04 | 22.50 | 22.35 | 22.58 | 22.21 | 58511.0 | 600118 |
80 | 2018-05-07 | 22.49 | 22.70 | 22.71 | 22.30 | 58248.0 | 600118 |
81 | 2018-05-08 | 22.80 | 23.07 | 23.45 | 22.75 | 115629.0 | 600118 |
最后的圖片:
# 金融數(shù)據(jù)每日摘要圖表fig, ax = plt.subplots(figsize=(8, 5))fig.subplots_adjust(bottom=0.2)mpf._plot_day_summary(ax, quotes, colorup='r', colordown='g')plt.grid(True)ax.xaxis_date()# dates on the x-axisax.autoscale_view()plt.setp(plt.gca().get_xticklabels(), rotation=30)plt.title('金融數(shù)據(jù)每日摘要圖表')
蠟燭圖和成交量柱狀圖組合而成的圖表
# 蠟燭圖和成交量柱狀圖組合而成的圖表fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(8, 6))mpf.candlestick_ochl(ax1, quotes, width=0.6, colorup='r', colordown='g', alpha=0.8)ax1.set_title('中國(guó)衛(wèi)星')ax1.set_ylabel('index level')plt.grid(True)ax1.xaxis_date()plt.bar(quotes[:,0],quotes[:,5],width=0.5)ax2.set_ylabel('volume')ax2.grid(True)plt.setp(plt.gca().get_xticklabels(), rotation=30)
(模擬)隱含波動(dòng)率的 3D 曲面圖
# strike = np.linspace(50, 150, 24)ttm = np.linspace(0.5, 2.5, 24)strike, ttm = np.meshgrid(strike, ttm)iv = (strike - 100) ** 2 / (100 * strike) / ttm# generate fake implied volatilitiesfrom mpl_toolkits.mplot3d import Axes3Dfig = plt.figure(figsize=(9, 6))ax = fig.gca(projection='3d')surf = ax.plot_surface(strike, ttm, iv, rstride=2, cstride=2, cmap=plt.cm.coolwarm, linewidth=0.5, antialiased=True)ax.set_xlabel('strike')ax.set_ylabel('time-to-maturity')ax.set_zlabel('implied volatility')fig.colorbar(surf, shrink=0.5, aspect=5)
plot_surface參數(shù)
參數(shù) | 描述 |
---|---|
X,Y,Z | 2D數(shù)組形式的數(shù)據(jù)值 |
rstride | 數(shù)組行距(步長(zhǎng)大?。?/td> |
cstride | 數(shù)組列距(步長(zhǎng)大?。?/td> |
color | 曲面塊顏色 |
cmap | 曲面塊顏色映射 |
facecolors | 單獨(dú)曲面塊表面顏色 |
norm | 將值映射為顏色的 Nonnalize實(shí)例 |
vmin | 映射的最小值 |
vmax | 映射的最大值 |
(模擬)隱含波動(dòng)率的 3D 散點(diǎn)圖
#(模擬)隱含波動(dòng)率的 3D 散點(diǎn)圖fig = plt.figure(figsize=(8, 5))ax = fig.add_subplot(111,projection='3d')ax.view_init(30,60)ax.scatter(strike, ttm, iv, zdir='z',s=25,c='b',marker='^')ax.set_xlabel('strike')ax.set_ylabel('time-to-maturity')ax.set_zlabel('implied volatility')
end
聯(lián)系客服