目录
- hist+scatter
- hist2d
hist+scatter
如果想描述二维数据的分布特征,那么一个直方图显然是不够用的,为此可使用两个直方图分别代表x
和y
方向上的分布情况,同时透过散点图查看其整体的分布特征。
下面创建一组二元高斯分布的数据,用于直方图测试。多元高斯分布的主要参数仍为期望和方差,但所谓多元分布,在坐标层面的表现就是坐标轴的个数,也就是向量维度。所以N个元素对应N维向量,也就有N个期望;而方差则进化为了协方差矩阵
import numpy as np import matplotlib.pyplot as plt mean = [0, 0] cov = [[0, 1], [10, 0]] x, y = np.random.multivariate_normal(mean, cov, 5000).T
其中,x,y
就是待统计的数据。
fig = plt.figure() gs = fig.add_gridspec(2, 2, width_ratios=(4, 1), height_ratios=(1, 4)) ax = fig.add_subplot(gs[1, 0]) ax.scatter(x, y, marker='x') # 散点图绘制 xHist = fig.add_subplot(gs[0, 0], sharex=ax) xHist.tick_params(axis="x", labelbottom=False) yHist = fig.add_subplot(gs[1, 1], sharey=ax) yHist.tick_params(axis="y", labelleft=False) binwidth = 0.25 lim = (int(np.max(np.abs([x,y]))/0.25) + 1) * 0.25 bins = np.arange(-lim, lim + binwidth, binwidth) xHist.hist(x, bins=bins) yHist.hist(y, bins=bins, orientation='horizontal') plt.show()
其中,tick_params
用于取消直方图左侧和下面的坐标刻度,效果如下
hist2d
相比之下,hist2d
可以更加便捷地绘制直方图,并以图像的形式反馈回来
当然,也可以把hist+scatter图中的散点图代之以hist2d
fig = plt.figure() gs = fig.add_gridspec(2, 2, width_ratios=(4, 1), height_ratios=(1, 4)) ax = fig.add_subplot(gs[1, 0]) ax.hist2d(x, y, bins=40) # 散点图绘制 xHist = fig.add_subplot(gs[0, 0], sharex=ax) xHist.tick_params(axis="x", labelbottom=False) yHist = fig.add_subplot(gs[1, 1], sharey=ax) yHist.tick_params(axis="y", labelleft=False) binwidth = 0.25 lim = (int(np.max(np.abs([x,y]))/0.25) + 1) * 0.25 bins = np.arange(-lim, lim + binwidth, binwidth) xHist.hist(x, bins=bins) yHist.hist(y, bins=bins, orientation='horizontal') plt.show()
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)