1 函数:频数折线图
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)
【具体应用】
1. 绘制数学函数
# 第一步:定义求取积分的函数
def func(x):
return 0.5 * np.exp(x) + 1 # 指数函数
# 第二步:定义积分区间,生成必须得数值
a, b = 0.5 , 1.5
x = 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)
# 第四步:使用Polygon函数生成阴影部分,表示积分面积
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在图表上添加数学公式和一些坐标轴标签
plt.text(0.5 * (a + b),1,r"$\int_a^b f(x)\mathrm{d}x$",horizontalalignment='center',fontsize=20)
plt.figtext(0.9, 0.075, "$x$")
plt.figtext(0.075,0.9,"$f(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)
- 金融学图表
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线数据
data_of = data[:60] # 只取前60份数据
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转换为浮点型
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__)
#设置x轴为时间格式,否则x轴显示的将是类似于‘736268’这样的转码后的数字格式
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) # 网格设置
plt.title("k线图")
ax.autoscale_view()
ax.xaxis_date()
2.2)3D绘图
波动率平面:同时展示许多到期日和行权价的隐含波动率
# 根据两个1维ndarray对象转换为一个二维数组
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
# 生成波动率图表
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)
【拓展】
- Bokeh - Python的交互式网络绘图
References
Python技能 | Matplotlib数据可视化