注:Python数据分析再学习
1. matplotlib API入门
1.1 Figure和Subplot
## 创建一幅图
fig = plt.figure()
## 创建多幅图
fig, axes = plt.subplots(2, 3)
1.2 调整subplot周围的间距
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)
plt.subplots_adjust(wspace = 0, hspace = 0)
1.3 颜色、标记和线型
from numpy.random import randn
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')
plt.legend(loc= 'best')
注:标记类型和线型必须在颜色的后面
1.4 设置标题、轴标签、刻度和刻度标签
## 创建图形
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.random.randn(1000).cumsum())
## 设置x轴刻度
ticks = ax.set_xticks([0, 250, 500, 750, 1000])
## 设置x轴刻度标签
labels = ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'], rotation = 30, fontsize = 'small')
## 设置x轴名称
ax.set_xlabel('Stages')
## 设置标题
ax.set_title('My first matplotlib plot')
## 批量设定绘图选项
prop = {'title': 'My first matplotlib plot', 'xlabel': 'Stages'}
ax.set(**props)
1.5 添加图例
最简单的方法就是在添加subplot的时候传入label参数
from numpy.random import randn
fig = plt.figure(); ax = fig.add_subplot(1, 1, 1)
ax.plot(randn(1000).cumsum(), 'k', label = 'one')
ax.plot(randn(1000).cumsum(), 'k--', label = 'two')
ax.plot(randn(1000).cumsum(), 'k.', label = 'three')
## 调用ax.legend()或者plt.legend()均可
ax.legend(loc = 'best')
2. 使用pandas和seaborn绘图
2.1 线形图
s = pd.Series(np.random.randn(10).cumsum())
s.plot()
plot参数列表
参数 | 说明 |
---|---|
label | 用于图例的标签 |
ax | 要在其上进行绘制的matplotlib subpot对象 |
style | 将要传给matplotlib的风格字符串(如’ko–’) |
alpha | 图表的填充不透明度 |
kind | 可以是’line’, ‘bar’, ‘barh’, ‘kde’ |
logy | 在Y轴上使用对数标尺 |
use_index | 将对象的索引用作刻度标签 |
rot | 旋转刻度标签 |
xticks | 用作X轴刻度的标签 |
yticks | 用作Y轴刻度的标签 |
xlim | X轴的界限 |
ylim | Y轴的界限 |
grid | 显示轴网格线 |
df = pd.DataFrame(np.random.randn(100, 4).cumsum(0), columns = ['A', 'B', 'C', 'D'], index = np.arange(100))
df.plot()
DataFrame中的plot参数
参数 | 说明 |
---|---|
subplots | 将各个DataFrame列绘制到单独的subplot中 |
sharex | 如果subplots = True,则共用同一个x轴,包括刻度和界限 |
sharey | 如果subplots = True,则共用同一个Y轴 |
figsize | 表示图像大小的元组 |
title | 表示图像标题的字符串 |
legend | 添加一个subpot图例(默认为True) |
sort_columns | 以字母表顺序绘制各列,默认使用当前列的顺序 |
2.2 柱状图
## Series对象
fig, axes = plt.subplots(2, 1)
data = pd.Series(np.random.randn(16), index = list('abcdefghijklmnop'))
data.plot.bar(ax = axes[0], color = 'k', alpha = 0.5)
data.plot.barh(ax = axes[1], color = 'k', alpha = 0.5)
## DataFrame对象
df = pd.DataFrame(np.random.randn(6, 4), index = ['one', 'two', 'three', 'four', 'five', 'six'], columns = pd.Index(['A', 'B', 'C', 'D'], name = 'Genus'))
df.plot.bar()
df.plot.barh(stacked = True, alpha = 0.5)
## 一个例子
tips = pd.read_csv('examples/tips.csv')
party_counts =pd.crosstab(tips['day'], tips['size'])
party_counts = party_counts.loc[:, 2:5]
party_pcts = party_counts.div(party_counts.sum(axis = 1), axis = 0)
### 这里比较难,是先对每一行求和,在让各元素除以这一行的和,重点是axis=0还是axis=1的问题
2.3 直方图和密度图
tips['size'].plot.hist()
tips['size'].plot.density()
## 同时画直方图与密度图
import seaborn
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 = 'b')
2.4 散布图或点图
## 数据预处理
macro = pd.read_csv('examples/macrodata.csv')
data = macro[['cpi', 'm1', 'tbilrate', 'unemp']]
trans_data = np.log(data).diff().dropna()
## 散布图与线性回归
sns.regplot('m1', 'unemp', data = trans_data)
## 散步图矩阵
sns.pairplot(trans_data, diag_kind = 'kde')