本篇札记主要是整理于《利用
Python
进行数据分析-第二版》的第九章,本章中讲解了可视化的工具:matplotlib
和seaborn
。
导入库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline # 一定要导入进来,否则无法出图
简单图形
data = np.arange(10)
plt.plot(data)

- 绘制子图
fig = plt.figure()
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)

- 随机散点图
plt.plot(np.random.randn(50).cumsum(), 'k--')

复杂点图形
fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)
for i in range(2):
for j in range(2):
axes[i, j].hist(np.random.randn(500), bins=50, color='r', alpha=0.5)
plt.subplots_adjust(wspace=0, hspace=0)

- 随机漫步
from numpy.random import randn
# 生成0到30的随机数
plt.plot(randn(30).cumsum(), 'ko--')

data = np.random.randn(30).cumsum()
plt.plot(data, 'k--', label='Default')
plt.plot(data, 'k-', drawstyle='steps-post', label='steps-post')
# best表示在最合适的位置自动添加图例
plt.legend(loc='best')

标题和轴标签
# 代码放在同一个cell中
# 创建fig实例,调用figure类
fig = plt.figure()
# 创建子图
ax = fig.add_subplot(1, 1, 1)
# 作图
ax.plot(np.random.randn(1000).cumsum())
# 数据的刻度设置;
ticks = ax.set_xticks([0, 250, 500, 750, 1000])
# 刻度标签和标签旋转角度
labels = ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'],
rotation=45, fontsize='medium')
#
ax.set_title('My first matplotlib plot')
ax.set_xlabel('Stages')
# 批量设定
# props = {
# 'title': 'My first matplotlib plot',
# 'xlabel': 'Stages'
# }
# ax.set(**props)

# 代码需要放在同一个单元格中,否则不出图
from numpy.random import randn
fig = plt.figure(); ax = fig.add_subplot(1, 1, 1)
ax.plot(randn(1000).cumsum(), 'r', label='one')
ax.plot(randn(1000).cumsum(), 'b--', label='two')
ax.plot(randn(1000).cumsum(), 'g.', label='three')
# 图例位置,best自动选择最好的位置
ax.legend(loc='best')
plt.show()

块图
# 关于块:创建块对象shp,传给add_patch(shp)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
# (0.4, 0.75), 0.4, 0.15:起始位置,长,宽; alpha=0.8:颜色深度
rect = plt.Rectangle((0.4, 0.75), 0.4, 0.15, color='g', alpha=0.8)
circ = plt.Circle((0.7, 0.4), 0.15, color='b', alpha=0.3)
pgon = plt.Polygon([[0.15, 0.15], [0.35, 0.4], [0.2, 0.6]],color='r', alpha=0.5)
ax.add_patch(rect)
ax.add_patch(circ)
ax.add_patch(pgon)
# 图片保存
plt.savefig('test.png', dpi=400, bbox_inches='tight')

matplotlib配置
- 配置文件:matplotlibrc(位于matplotlib/mpl-data⽬录中)
- 通过全局参数进行配置;管理图像大小、边距、字体大小等
- plt.rc("figure", figsize=(10, 10)),第一个参数是希望自定义的对象
-
如'figure'、'axes'、'xtick'、'ytick'、'grid'、'legend',可以写成字典形式
image.png
使⽤pandas和seaborn绘图
- pandas内置方法简化DF和S绘图
- seaborn:静态图形库
- Bokeh/Plotly:动态交互图,⽤于⽹⻚浏览器。
S的plot绘制
# 线性图:S的plot方法
s = pd.Series(np.random.randn(10).cumsum(), index=np.arange(0, 100, 10))
s.plot()
# xticks和xlim调整x轴信息,y轴同理

DF的plot图形绘制
# DF的plot方法:会在⼀个subplot中为各列绘制⼀条线,并⾃动创建图例
df = pd.DataFrame(np.random.randn(10, 4).cumsum(0),
columns = ['A', 'B', 'C', 'D'],
index = np.linspace(0, 100, 10))
df.plot()

柱状图



堆积柱状图
- 设置stack=True
- plot.barh生效

学习Seaborn




直方图和密度图
- hist:直⽅图(histogram)是⼀种可以对值频率进⾏离散化显示的柱状图
- density:将该分布近似为⼀组核(如正态分布);也被称作KDE(Kernel Density Estimate,核密度图)


散点图Scatter
- 观察两个一维数据序列之间的关系
- regplot函数绘制散布图 + 线性回归的线
-
pairplot函数绘制散布图矩阵:对角线上放置每个变量的直方图或者密度图
image.png


分⾯⽹格(facet grid)和类型数据
- 多个变量的图形绘制在同个网格中:分面图
- 使用函数factorplot函数


# 盒图:中位数、四分位数、异常值
sns.factorplot(x='tip_pct', y='day', kind='box',
data=df[df.tip_pct < 0.5])

网友评论