2.饼图(Pie Charts)
- 绘制单分类变量的相对频率
# code for the pie chart seen above
sorted_counts = pokemon['generation_id'].value_counts()
plt.pie(sorted_counts, labels = sorted_counts.index, startangle = 90,
counterclock = False);
plt.axis('square')
直方图(Histograms)
- 直方图用于绘制数字变量的分布
- 每一个柱是某一区间内点的个数
- 条形图是用来绘制分类变量的分布的
如果数据位于边缘
,它将在右侧
的区间内计数
(除
了最右侧
)
默认
将数据分为10
个区间,
可以使用df.describe()来获取数据的统计信息,进而确定合适的边界和划分,然后利用bins来复制
bin_edges = np.arange(0,pokemon['attack'].max()+1,10)
plt.hist(data = pokemon, x = 'attack',bins = bin_edges);
子图
绘制
- plt.figure(figsize = [10,5])
- 子图中
较大图形
的尺寸
- 子图中
- plt.subplot(
row
= 1,col
= 2,subplot
=1)- 一行,两列,子图编号
- 子图编号相同时,绘制到同一个图内
plt.figure(figsize = [10, 5]) # larger figure size for subplots
# histogram on left, example of too-large bin size
plt.subplot(1, 2, 1) # 1 row, 2 cols, subplot 1
bin_edges = np.arange(0, df['num_var'].max()+4, 4)
plt.hist(data = df, x = 'num_var', bins = bin_edges)
# histogram on right, example of too-small bin size
plt.subplot(1, 2, 2) # 1 row, 2 cols, subplot 2
bin_edges = np.arange(0, df['num_var'].max()+1/4, 1/4)
plt.hist(data = df, x = 'num_var', bins = bin_edges)
还可以使用seaborn中的
distplot
来绘制直方图
bin_edges = np.arange(0,pokemon['attack'].max()+1,10)
sb.distplot(pokemon['attack'],bins=bin_edges);
但是他会采用核密度
的方式,但可以更改
bin_edges = np.arange(0, df['num_var'].max()+1, 1)
sb.distplot(df['num_var'], bins = bin_edges, kde = False,
hist_kws = {'alpha' : 1})
matplot的一些常用参数设置
matplot可视化的基础
是一个Figure
对象,每个图中包含一个或多个Axes对象,每个Axes对象包含许多个其他的表示图的元素
调用plt.hist作图的过程可以看做是这样的:
- 创建一个figure
- 在figure上添加一个Axes
- 在Axes上画图
我们可以依照此顺序来控制图形的布局:
解析以下代码: - figure()创建了一个
画布对象
fig - figure有一个方法是
.add_axes()
- 该方法需要一个
list
作为参数指定轴的尺寸
(其值为整个figure相同行或列的百分比) - 列表的前两个元素是axes左下角的位置,最后两个元素指定axes的宽度和高度
fig = plt.figure()
ax = fig.add_axes([.125, .125, .775, .755])
ax.hist(data=pokemon, x='special-defense');
要将axes
对象与seaborn
一起使用,通常seaborn会有ax参数
以指定绘制图形的轴
subplot
- 首先,matplotlib和seaborn自动选取最近的fig
- 其次,subplot指定的是axes
plt.figure(figsize = [10, 5]) # larger figure size for subplots
# example of somewhat too-large bin size
plt.subplot(1, 2, 1) # 1 row, 2 cols, subplot 1
bin_edges = np.arange(0, df['num_var'].max()+4, 4)
plt.hist(data = df, x = 'num_var', bins = bin_edges)
# example of somewhat too-small bin size
plt.subplot(1, 2, 2) # 1 row, 2 cols, subplot 2
bin_edges = np.arange(0, df['num_var'].max()+1/4, 1/4)
plt.hist(data = df, x = 'num_var', bins = bin_edges)
对于离散变量可以通过增加rwidth来使其分布散开
bin_edges = np.arange(1.5, 12.5+1, 1)
plt.hist(die_rolls, bins = bin_edges, rwidth = 0.7)
plt.xticks(np.arange(2, 12+1, 1))
统计描述,异常值,轴限制
当数据分布范围较大
时,为了覆盖较小值和较大值,往往会在坐标轴上出现很多空隙
,所以采用倍数差
,而非算术差
,对数分布
当面对偏斜分布时:
plt.hist(data=df,
x='weight',
bins=np.arange(df['weight'].values.min() - 1,
df['weight'].values.max() + 1, 20));
需要将坐标的增长变为倍数差
plt.hist(data=df,
x='weight',
bins=10 ** np.arange(-1,
3+0.1, 0.1))
plt.xscale('log');