常用模块与设置
import pandas as pd
from pandas import DataFrame, Series
import numpy as np
np.random.seed(12345)
import matplotlib.pyplot as plt
# matplotlib的交互绘图,在XPython内核下不可用
%matplotlib widget
plt.rc("figure", figsize=(10, 6))
PREVIOUS_MAX_ROWS = pd.options.display.max_rows
pd.options.display.max_rows = 20
np.set_printoptions(precision=4, suppress=True)
'''弹出图像窗口'''
%matplotlib
matplotlib库--绘图与可视化
import matplotlib.pyplot as plt
修改matplotlib配置--rc(默认参数的设置)
(group, **kwargs)
group: 自定义的组建(figure, axes, xtick, ytick, grid, legend
rc('lines', linewidth=2, color='r')
Alias Property
===== =================
'lw' 'linewidth'
'ls' 'linestyle'
'c' 'color'
'fc' 'facecolor'
'ec' 'edgecolor'
'mew' 'markeredgewidth'
'aa' 'antialiased'
===== =================
plt.rc("figure", figsize=(4, 3))
创建图片与子图
figure--创建或激活图片
num=None,(默认自动+1) # 图片编号
figsize=None,(默认为rc设置) # (宽,高),单位为英寸
dpi=None,(默认80) # 分辨率(每英寸有多少个
facecolor=None, # 背景颜色
edgecolor=None, # 边框颜色
frameon=True, # 是否显示边框
FigureClass=<class 'matplotlib.figure.Figure'>,
clear=False, # 如果图片已存在其内容是否被清楚
**kwargs,
plt.figure(figsize=(4,3),facecolor=None,edgecolor='red')
plt.plot(np.random.randn(100))
plt.figure(num=7,clear=True)
add_subplot--添加子图
(*args, **kwargs)
- *args # int(3位数的整数), (int, int, index), or
.SubplotSpec
, default: (1, 1, 1)
fig=plt.figure()
fig.add_subplot(221)
fig.add_subplot(2,2,2)
plt.plot(np.random.randn(100).cumsum()) # 无指定子图时,在最后一个子图上绘图
subplot--添加子图
(*args, **kwargs)
*args : int, (int, int, *index*), or `.SubplotSpec`, default: (1, 1, 1)
projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional # 图表类型
polar : bool, default: False
sharex, sharey : `~.axes.Axes`, optional
label : str
plt.figure()
projections=[None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear']
i=0
for j in projections:
i+=1
plt.subplot(2,4,i,projection=j)
subplots--同时创建图片与子图
nrows=1,
ncols=1,
*, # figure的参数
sharex=False, # 共享x轴的子图
sharey=False, # 共享y轴的子图
squeeze=True, # array of `~matplotlib.axes.Axes`是否增加维度(False-一维,True:(nrow,ncols)维)
subplot_kw=None, dict # 字典里的关键字被传递给add_subplot函数去调用图像类型(projection参数)
gridspec_kw=None, dict # 将关键字传递给Gridspec构造函数,该构造函数用于放置子图的网络。
**fig_kw,
- sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False
- 返回图片和子图数组集合
- subplot_kw # 目前只适应出polar有效
fig, axs = plt.subplots(2,4,subplot_kw=dict(polar=True)) # 极坐标系
fig,axes=plt.subplots(2,3)
print(fig)
axes
plt.subplots(2,2)
显示图表交互窗口--show
show(*args, **kwargs)
block : bool, optional # 是否所有交互图表关闭后才返回命令行(默认: 非交互模式下-True,交互模式下-False)
- 在交互模式下,语句执行后自动调用show()
plt.figure(num=5)
plt.show()
关闭figure窗口--close
(fig=None)
- fig : None or int or str or
.Figure
# None-当前,all-所有
plt.close('all')
保存图片到文件--savefig
fname : 文件完整名(推导存储格式)
dpi : float or 'figure', default: :rc:`savefig.dpi` # 分辨率
facecolor
edgecolor
format: 文件格式(png,pdf,svg,ps,eps.....)
bbox_inches : 要保存的图片范围('tight' 将会去除图片周围的空白)
plt.savefig('lele.png')
图表格式设置
[图片上传失败...(image-acb1b8-1632046662166)]!
图片与子图
gcf--返回当前状态下的figure对象
()
plt.gcf()
get_axes--从图片中获取axes对象
plt.gcf().get_axes()
gca--返回当前状态下的axes对象
gca(**kwargs)
plt.gca()
get_children--查看axes对象下的元素
plt.gca().get_children()
subplots_adjust--调整子图间距
left=None,
bottom=None,
right=None,
top=None,
wspace=None,
hspace=None,
plt.subplots(2,2,sharex=True,sharey=True)
plt.subplots_adjust(wspace=0,hspace=0)
title--设置子图标题
(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)
- fontdict(字体格式):
{'fontsize': rcParams['axes.titlesize'],
'fontweight': rcParams['axes.titleweight'],
'color': rcParams['axes.titlecolor'],
'verticalalignment': 'baseline',
'horizontalalignment': loc}
plt.subplots(2,2)
plt.title('lele')
plt.gcf()
set_title--子图标题
label,
fontdict=None,
loc=None,
pad=None,
*,
y=None,
**kwargs,
- {'fontsize': rcParams['axes.titlesize'],
'fontweight': rcParams['axes.titleweight'],
'color': rcParams['axes.titlecolor'],
'verticalalignment': 'baseline',
'horizontalalignment': loc} - pad : float, default: :rc:
axes.titlepad
fig=plt.figure()
ax1=fig.add_subplot(1,1,1)
ax1.plot(np.random.randn(1000).cumsum())
ax1.set_title('lele')
图例--legend
loc # 图例位置,如使用bbox_to_anchor,则该参数无效
bbox_to_anchor # 自定义图例位置
Fontsize # 字体大小
Frameon # 是否显示图例边框
Ncol # 图例的列数,默认1
Title # 图例标题
Shadow # 是否为图例添加阴影
Markerfirst # 图例标签在句柄右侧
Numpoints # 表示图例中句柄上的标记点的个数,一般设为1
Fancybox # 是否将图例边框的边角设置为圆形
Framealpha # 图例框的透明度
Borderpad # 图例框内边距
Labelspacing # 图例中条目之间的距离
Handlelength # 图例句柄的长度
=============== =============
Location String Location Code
=============== =============
'best' 0
'upper right' 1
'upper left' 2
'lower left' 3
'lower right' 4
'right' 5
'center left' 6
'center right' 7
'lower center' 8
'upper center' 9
'center' 10
=============== =============
plt.subplots()
data = np.random.randn(30).cumsum()
plt.plot(data, 'k--', label='Default')
plt.plot(data, 'k-', drawstyle='steps-post', label='steps-post')
plt.legend(loc='upper center')
plt.grid(
轴格式--set/set_xticks/set_xtickslabels/set_xlabel/set_xlim
- set_xticks(ticks, *, minor=False) # 刻度
- set_xticklabels(labels, *, fontdict=None, minor=False, **kwargs) # 刻度标签
- set(**kwargs) # 设置格式
rotation 旋转角度,fontsize 字体大小-small,medium,large)
{'fontsize': rcParams['axes.titlesize'],
'fontweight': rcParams['axes.titleweight'],
'verticalalignment': 'baseline',
'horizontalalignment': loc} - set_xlim # 刻度范围
left=None,
right=None,
emit=True,
auto=False,
*,
xmin=None,
xmax=None,
fig=plt.figure()
ax1=fig.add_subplot(1,1,1)
ax1.plot(np.random.randn(1000).cumsum())
ax1.set(**{'label':'lele','title':'lll','xlabel':'lele'})
ax1.legend()
ax1.set_xlim([0,1000])
fig=plt.figure()
ax1=fig.add_subplot(1,1,1)
ax1.plot(np.random.randn(1000).cumsum(),label='lele3')
ax1.set_xticks(range(0,1001,250))
ax1.set_xticklabels(['abcde','fffss','sddsss','sssd','sdwss'],rotation=30,fontsize='small')
ax1.set_xlabel('lele',rotation=180,fontsize='medium')
ax1.set_title('lele1')
ax1.legend(loc='upper center')
xlabel与ylabel--轴标签
(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)
plt.xlabel('lelex')
plt.ylabel('leley')
plt.gcf()
axis/xlim/ylim--轴的范围
(*args, emit=True, **kwargs)
([xmin, xmax, ymin, ymax])
plt.axis([0,2,3,5])
plt.gcf()
grid--设置x轴和y轴的主要和次要网格
(b=None, which='major', axis='both', **kwargs)
b: 有无网格线
which: 主/次网格线
axis: x轴和y轴网格线
color
linestyle
linewidth
alpha: 透明度
plt.grid(b=True)
plt.gcf()
注释
text--文本注释
(x, y, s, fontdict=None, **kwargs)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.text(0.5,0.5,'lele',color='r')
arrow--箭头注释
(x, y, dx, dy, **kwargs)
length_includes_head : bool, default: False
ax.arrow(0.5,0.5,0.3,0.3,facecolor='black', head_width=4, width=2, head_length=4)
annotate--包含文本与箭头的注释
(text, xy, *args, **kwargs)
- text # 注释内容
- xy : (float, float) 需标记注释的坐标
- xytext : (float, float), default: *xy* # 放置文本的坐标
- arrowprops : dict, optional arrowprops=dict(facecolor-填充色='black', headwidth-头部宽=4, width-尾部-宽=2, headlength-头部长=4), # xyy与xytext之间的箭头
horizontalalignment='left', verticalalignment='top')
from datetime import datetime
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
data = pd.read_csv('/Users/zhengdale/Documents/python/data/examples/spx.csv', index_col=0, parse_dates=True)
spx = data['SPX']
spx.plot(ax=ax, style='k-')
crisis_data = [
(datetime(2007, 10, 11), 'Peak of bull market'),
(datetime(2008, 3, 12), 'Bear Stearns Fails'),
(datetime(2008, 9, 15), 'Lehman Bankruptcy')
]
for date, label in crisis_data:
ax.annotate(label, xy=(date, spx.asof(date) + 75),
xytext=(date, spx.asof(date) + 225),
arrowprops=dict(facecolor='black', headwidth=4, width=2,
headlength=4),
horizontalalignment='left', verticalalignment='top')
# Zoom in on 2007-2010
ax.set_xlim(['1/1/2007', '1/1/2011'])
ax.set_ylim([600, 1800])
ax.set_title('Important dates in the 2008-2009 financial crisis')
图片
只有在一个代码快上连续执行才会都作用于一张图标上
points = np.arange(-5, 5, 0.01) # 1000 equally spaced points——坐标轴
xs, ys = np.meshgrid(points, points) # 向量的数组表示
z = np.sqrt(xs ** 2 + ys ** 2)
plt.figure()
plt.imshow(z, cmap=plt.cm.gray)
plt.colorbar()
plt.title("Image plot of $\sqrt{x^2 + y^2}$ for a grid of values")
imshow 可视化图形
X,
cmap=None,----colormap(颜色)
norm=None,
aspect=None,
interpolation=None,
alpha=None,
vmin=None,
vmax=None,
origin=None,
extent=None,
*,
filternorm=True,
filterrad=4.0,
resample=None,
url=None,
data=None,
**kwargs,
import numpy as np
points=np.arange(-5,5,0.1)
xs,ys=np.meshgrid(points,points)
z=np.sqrt(xs**2+ys**2)
f=plt.imshow(z,cmap=plt.cm.gray)
colorbar 给图表增加彩条
(mappable=None, cax=None, ax=None, **kw)
plt.colorbar(f)
title 添加标题
(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)
plt.title("Image plot of $\sqrt{x^2 + y^2}$ for a grid of values")
图形
绘制图形
- 图形只有添加到子图上才会显性
Rectangle--长方形
(xy, width, height, angle=0.0, **kwargs)
xy # 左下角点的坐标
angle # 旋转的角度
**kwargs # color, alpha(透明度)
Circle--圆形
(xy, radius=5, **kwargs)
Polygon--多边形
(xy, closed=True, **kwargs)
xy # N*2维数组
rect = plt.Rectangle((0.2, 0.75), 0.4, 0.15,facecolor='r', alpha=0.3)
circ = plt.Circle((0.7, 0.2), 0.15, color='b', alpha=0.3)
pgon = plt.Polygon([[0.15, 0.15], [0.35, 0.4], [0.2, 0.6]],
color='g', alpha=0.5)
pgon
添加到子图--add_patch
(p)
fig = plt.figure(figsize=(12, 6))
ax = fig.add_subplot(1, 1, 1)
ax.add_patch(rect)
ax.add_patch(circ)
ax.add_patch(pgon)
图表
plot--折线图(x,y)
(*args, scalex=True, scaley=True, data=None, **kwargs)
- 可传入多组数据(数组类数据)
- plot([x], y, [fmt], *, data=None, **kwargs)
- plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
- 二维数组/DataFrame
- 格式控制字符串顺序: 颜色-点型-线型
- 如果只控制"颜色", 格式控制字符串还可以输入英文全称, 如"red", 甚至是十六进制RGB字符串, 如"#FF0000". python可用的"颜色"大全
x,y数据参数
'''只有一列,默认为y,且x为range(y)与y一一对应'''
y=np.random.randn(100)
plt.figure()
plt.plot(y)
'''多组数据的表示'''
y=np.random.randn(100,2)
fig,axes=plt.subplots(2,1)
axes[0].plot(y)
x=list(range(100))
axes[1].plot(range(100),np.random.randn(100),range(100),np.random.randn(100))
'''多维度数轴,其轴向为一组数据'''
# 必须是同维度
plt.figure()
lst1=[[0,1,2],[3,4,5],[6,7,8]]
x=np.array(lst1)
lst2=[[2,3,2],[3,4,3],[4,5,4]]
y=np.array(lst2)
plt.plot(x,y,"bo--") #"b"为蓝色, "o"为圆点, ":"为点线
格式参数--color, marker, linestyle
**Markers**
============= ===============================
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**
============= ===============================
character description
============= ===============================
``'-'`` 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
============= ===============================
'''默认\b-'''
plt.subplots()
plt.plot(np.random.randn(100))
color=['b','g','r','c','m','y','k','w']
line_style=['-','--','-.',':']
marker=['.',',','o','v','^','<','>','1','2','3','4','s','p','*','h','H','+','x','D','d','|','_','.',',']
a=color+line_style+marker
y=np.random.permutation(5)*2
fig,axes=plt.subplots(3,len(marker))
for i in color:
axes[0,color.index(i)].plot(y,i,label=i)
for i in line_style:
axes[1,line_style.index(i)].plot(y,i)
for i in marker:
axes[2,marker.index(i)].plot(y,i)
plt.legend()
fig,axes=plt.subplots(2,2)
y=[2,3,2]
# 蓝色,线宽20,圆点,点尺寸50,点填充红色,点边缘宽度6,点边缘灰色
axes[1,1].plot(y,color="blue",linewidth=20,marker="o",markersize=50,
markerfacecolor="red",markeredgewidth=6,markeredgecolor="grey")
label--数据标签
只有调用plt.legend()放置标签函数,才会显示标签
plt.subplots()
data = np.random.randn(30).cumsum()
plt.plot(data, 'k--', label='Default')
plt.legend()
数据点之间如何连接--drawstle/steps-post
drawstle(默认线性内插,steps-post 阶梯形)
plt.subplots()
data = np.random.randn(30).cumsum()
plt.plot(data, 'k--', label='Default')
plt.plot(data, 'k-', drawstyle='steps-post', label='steps-post')
plt.legend(loc='upper center')
pandas库
通过plot属性调用matplotlib
绘图--plot(默认折线图)
-
Series对象
- label: 图例标签
- ax: 绘图所用的matplotlib子图对象,无则为当前活动子图
- style: 传递给matplotlib的样式字符串(颜色-标记-线条).如'ko--'
- alpha: [0,1]之间的透明度
- kind: 图表类型(默认折线图)--area, bar, barh, density, hist, kde, line, pie
- logy: 在y轴上使用对数缩放
- use_index: 使用索引刻度标签(默认True)
- rot: 刻度标签的旋转
- xticks: 用于x轴刻度的值
- yticks: 用于y轴刻度的值
- xlim: x轴的取值范围(如[0,10])
- ylim: y轴的范围
- grid: 展示网格线(默认打开)
-
DataFrame
- subplots: 将每一列绘制在独立的子图上
- sharex
- sharey
- figsize
- title
- legend: 默认True
- sort_culumns: 按字母顺序绘制各列(默认False)
等价于plot.line()
行索引用作x轴刻度标签,列索引作为标签
行索引的名称用作轴标签
plt.subplots()
s = pd.Series(np.random.randn(10).cumsum(), index=np.arange(0, 100, 10))
s.name='lele'
s.index.name='lele2'
s.plot(legend='lele1')
df = pd.DataFrame(np.random.randn(10, 4).cumsum(0),
columns=['A', 'B', 'C', 'D'],
index=np.arange(0, 100, 10))
df.plot()
plt.legend(loc='best')
柱状图--plot.bar(垂直)/plot.barh(水平)
stacked: 是否堆积(默认False)
fig, axes = plt.subplots(2, 1)
data = pd.Series(np.random.rand(16), index=list('abcdefghijklmnop'))
data.index.name='lele'
data.name='lele1'
data.plot.bar(ax=axes[0], color='k', alpha=0.7)
data.plot.barh(ax=axes[1], color='k', alpha=0.7)
df = pd.DataFrame(np.random.rand(6, 4),
index=['one', 'two', 'three', 'four', 'five', 'six'],
columns=pd.Index(['A', 'B', 'C', 'D'], name='Genus'))
fig,axes=plt.subplots(2,1)
df.plot.bar(ax=axes[0],)
df.plot.barh(ax=axes[1],stacked=True, alpha=0.5)
plt.close('all')
直方图--plot.hist
(by=None, bins=10, **kwargs)
by: 分组键
bins: 组数
- 每个类别的频数
plt.close('all')
tips = pd.read_csv('/Users/zhengdale/Documents/python/data/examples/tips.csv')
tips['tip_pct'] = tips['tip'] / (tips['total_bill'] - tips['tip'])
tips['tip_pct'].plot.hist(bins=50)
密度图--plot.density / plot.kde
- 通过计算可能产生观测数据的概率分布估而产生
- density (bw_method=None, ind=None, **kwargs)
- 近似为'内核'的混合
- kde (bw_method=None, ind=None, **kwargs)
- 传统法定混合估计法估计
plt.close('all')
tips['tip_pct'].plot.density()
plt.close('all')
tips['tip_pct'].plot.kde()
seaborn库
- 统计分析常用可视化库
import seaborn as sns
设置
主题设置--set
(*args, **kwargs)
- 空值为默认设置
sns.set(style='whitegrid')
图表
柱状图--barplot
*,
x=None, # 在data中的变量名
y=None, # 在data中的变量名
hue=None, # 在data中的变量名
data=None, DataFrame, array, or list of arrays
order=None, # 指定分类顺序
hue_order=None, # 分类的类别(字符串列表)
estimator=<function mean at 0x7f91982a0d30>, # 应用在类组内的统计函数
ci=95, # 置信区间大小,'sd'--跳过bootstrapping并绘制标准差; None--不执行bootstrapping,并且不绘制错误条
n_boot=1000, # 计算置信区间时使用的引导迭代函数
units=None, #
seed=None,
orient=None,(v/h) # 图形的显示方向
color=None,
palette=None, # 设置hue指定的变量的不同级别颜色
saturation=0.75, # 饱和度
errcolor='.26', # 表示置信区间的线条颜色
errwidth=None, # 误差线宽度
capsize=None, # 误差线上横线的大小
dodge=True, # 使用色调嵌套时,是否沿分类轴移动元素
ax=None,
**kwargs,
plt.close('all')
tips = pd.read_csv('/Users/zhengdale/Documents/python/data/examples/tips.csv')
tips['tip_pct'] = tips['tip'] / (tips['total_bill'] - tips['tip'])
sns.barplot(x='tip_pct', y='day', data=tips, orient='h')
plt.close('all')
sns.barplot(x='tip_pct', y='day', hue='time', data=tips, orient='h')
直方图和连续密度估计--distplot
a=None,
bins=None, # 分组数
hist=True, # 显示直方图**
kde=True, # 显示密度图
rug=False, # 是否生成观测值的小细条
fit=None, (norm) # 控制拟合的参数分布图
hist_kws=None,
kde_kws=None,
rug_kws=None,
fit_kws=None,
color=None,
vertical=False,
norm_hist=False, # 直方图显示密度而非计数
axlabel=None,
label=None,
ax=None,
x=None,
plt.figure()
comp1 = np.random.normal(0, 1, size=200)
comp2 = np.random.normal(10, 2, size=200)
values = pd.Series(np.concatenate([comp1, comp2]))
sns.distplot(values, bins=100, color='k') #Join a sequence of arrays along an existing axis.
散点图
regplot--散点图+回归线
*,
x=None,
y=None,
data=None,
x_estimator=None,
x_bins=None,
x_ci='ci',
scatter=True,
fit_reg=True,
ci=95,
n_boot=1000,
units=None,
seed=None,
order=1,
logistic=False,
lowess=False,
robust=False,
logx=False,
x_partial=None,
y_partial=None,
truncate=True,
dropna=True,
x_jitter=None,
y_jitter=None,
label=None,
color=None,
marker='o',
scatter_kws=None,
line_kws=None,
ax=None,
macro = pd.read_csv('/Users/zhengdale/Documents/python/data/examples/macrodata.csv')
data = macro[['cpi', 'm1', 'tbilrate', 'unemp']]
trans_data = np.log(data).diff().dropna()
trans_data[-5:]
plt.figure()
sns.regplot('m1', 'unemp', data=trans_data)
plt.title('Changes in log %s versus log %s' % ('m1', 'unemp'))
pairplot--散点图+每个变量的直方图或密度估计
sns.pairplot(trans_data, diag_kind='kde', plot_kws={'alpha': 0.2})
分面网格--factorplot
- kind: 图表类型
sns.factorplot(x='day', y='tip_pct', hue='time', col='smoker',
kind='bar', data=tips[tips.tip_pct < 1])
sns.factorplot(x='day', y='tip_pct', row='time',
col='smoker',
kind='bar', data=tips[tips.tip_pct < 1])
sns.factorplot(x='tip_pct', y='day', kind='box',
data=tips[tips.tip_pct < 0.5])