本篇札记主要是整理于《利用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)
image.png
fig = plt.figure()
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)
image.png
plt.plot(np.random.randn(50).cumsum(), 'k--')
image.png
复杂点图形
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)
image.png
from numpy.random import randn
plt.plot(randn(30).cumsum(), 'ko--')
image.png
data = np.random.randn(30).cumsum()
plt.plot(data, 'k--', label='Default')
plt.plot(data, '', drawstyle='steps-post', label='steps-post')
plt.legend(loc='best')
image.png
标题和轴标签
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')
image.png
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')
ax.legend(loc='best')
plt.show()
image.png
块图
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
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')
image.png
matplotlib配置
使⽤pandas和seaborn绘图
- pandas内置方法简化DF和S绘图
- seaborn:静态图形库
- Bokeh/Plotly:动态交互图,⽤于⽹⻚浏览器。
S的plot绘制
s = pd.Series(np.random.randn(10).cumsum(), index=np.arange(0, 100, 10))
s.plot()
image.png
DF的plot图形绘制
df = pd.DataFrame(np.random.randn(10, 4).cumsum(0),
columns = ['A', 'B', 'C', 'D'],
index = np.linspace(0, 100, 10))
df.plot()
image.png
柱状图
image.png
image.png
image.png
堆积柱状图
image.png
学习Seaborn
image.png
image.png
image.png
image.png
直方图和密度图
- hist:直⽅图(histogram)是⼀种可以对值频率进⾏离散化显示的柱状图
- density:将该分布近似为⼀组核(如正态分布);也被称作KDE(Kernel Density Estimate,核密度图)
image.png
image.png
散点图Scatter
image.png
image.png
分⾯⽹格(facet grid)和类型数据
- 多个变量的图形绘制在同个网格中:分面图
- 使用函数factorplot函数
image.png
image.png
sns.factorplot(x='tip_pct', y='day', kind='box',
data=df[df.tip_pct < 0.5])
image.png