1 函數(shù):頻數(shù)折線圖
def freq_poly(x, bins=10, **kwargs)
""" Custom frequency polygon/line plot code. """
#set bin edges if none or int specified
if type(bins) == int:
bins = np.linspace(x.min(), x.max(), bins+1)
bin_centers = (bin_edges[1:] + bin_edges[:-1]) / 2
#compute counts
data_bins = pd.cut(x, bins, right = False, include_lowest = True)
counts = x.groupby(data_bins).count()
#create plot
plt.errorbar(x=bin_centers, y=counts, **kwargs)
bin_edges = np.arange(-3, df['num_var'].max()+1/3, 1/3)
g = sb.FacetGrid(data=df, hue='cat_var', size=5)
g.map(freq_poly, 'num_var', bins=bin_edges)
g.add_legend()

折線圖:多變量
2 plt.scatter沒有jitter屬性
def rand_jitter(arr):
stdev = .01*(max(arr)-min(arr))
return arr + np.random.randn(len(arr)) * stdev
def jitter(x, y, s=20, c='b', marker='o', cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, hold=None, **kwargs):
return scatter(rand_jitter(x), rand_jitter(y), s=s, c=c, marker=marker, cmap=cmap, norm=norm, vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths, verts=verts, hold=hold, **kwargs)
【具體應(yīng)用】
1. 繪制數(shù)學(xué)函數(shù)
# 第一步:定義求取積分的函數(shù)
def func(x):
return 0.5 * np.exp(x) + 1 # 指數(shù)函數(shù)
# 第二步:定義積分區(qū)間,生成必須得數(shù)值
a, b = 0.5 , 1.5
x = np.linspace(0,2)
y = func(x)
# 第三步:繪制函數(shù)圖像
fig, ax = plt.subplots(figsize=(7,5))
plt.plot(x,y,'b',linewidth=2)
plt.ylim(ymin=0)
# 第四步:使用Polygon函數(shù)生成陰影部分,表示積分面積
Ix = np.linspace(a, b)
Iy = func(Ix)
verts = [(a,0)] + list(zip(Ix, Iy)) + [(b, 0)]
poly = plt.Polygon(verts,facecolor='0.7',edgecolor='0.5')
ax.add_patch(poly)
# 第五步:使用plt.text和plt.figtext在圖表上添加數(shù)學(xué)公式和一些坐標(biāo)軸標(biāo)簽
plt.text(0.5 * (a + b),1,r"$\int_a^b f(x)\mathrmu0z1t8osx$",horizontalalignment='center',fontsize=20)
plt.figtext(0.9, 0.075, "$x$")
plt.figtext(0.075,0.9,"$f(x)$")
# 第六步:設(shè)置刻度標(biāo)簽以及添加網(wǎng)格
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)

積分圖 知乎@十維教育
- 金融學(xué)圖表
2.1)燭柱圖
import mpl_finance as mpf
import matplotlib.pyplot as plt
import mpl_finance as mpf
import tushare as ts
import pandas as pd
from matplotlib.pylab import date2num
from dateutil.parser import parse
import numpy as np
import matplotlib.dates as mdate
data = ts.get_k_data('000001') # 獲取平安的k線數(shù)據(jù)
data_of = data[:60] # 只取前60份數(shù)據(jù)
fig, ax = plt.subplots(figsize=(15, 7))
__colorup__ = "r"
__colordown__ = "g"
# 圖表顯示中文
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']
qutotes = []
for index, (d, o, c, h, l) in enumerate(
zip(data_of.date, data_of.open, data_of.close,
data_of.high, data_of.low)):
# 時間需要通過date2num轉(zhuǎn)換為浮點型
d = date2num(parse(d))
# 日期,開盤,收盤,最高,最低組成tuple對象val
val = (d, o, c, h, l)
# 加val加入qutotes
qutotes.append(val)
# 使用mpf.candlestick_ochl進行蠟燭繪制,ochl代表:open,close,high,low
mpf.candlestick_ochl(ax, qutotes, width=0.8, colorup=__colorup__,colordown=__colordown__)
#設(shè)置x軸為時間格式,否則x軸顯示的將是類似于‘736268’這樣的轉(zhuǎn)碼后的數(shù)字格式
ax.xaxis.set_major_formatter(mdate.DateFormatter('%Y-%m-%d'))
plt.xticks(pd.date_range('2016-08-01','2016-11-30',freq='W'),rotation=60)
plt.grid(True) # 網(wǎng)格設(shè)置
plt.title("k線圖")
ax.autoscale_view()
ax.xaxis_date()

燭柱圖 知乎@十維教育
2.2)3D繪圖
波動率平面:同時展示許多到期日和行權(quán)價的隱含波動率
# 根據(jù)兩個1維ndarray對象轉(zhuǎn)換為一個二維數(shù)組
strike = np.linspace(50,150,24)
ttm = np.linspace(0.5,2.5,24)
strike,ttm = np.meshgrid(strike,ttm)
# 產(chǎn)生一組虛假的隱含波動率
iv = (strike - 100) ** 2/ (100 * strike) / ttm
# 生成波動率圖表
fig = 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)

3D繪圖 知乎@十維教育
【拓展】
- Bokeh - Python的交互式網(wǎng)絡(luò)繪圖