异步社区

异步社区是国内领先的IT专业图书社区,由人民邮电出版社主办,致力于优质学习内容的出版和分享。

34篇博客

使用正确的图表理解数据(六):使用散点图和直方图下篇

异步社区2018-12-28 13:50
7.7.3 工作原理
在上面的输出中,我们清楚地看到在不同的数据集合之间是否存在相关性。其中,第二幅(右上)图显示了数据集合d1和d1自身(显然地)之间理想的正相关。第四幅(右下)图表明数据集合间存在一个正相关,但不是理想正相关。我们用d1和d(随机的)构建的这个数据集合来模拟两个相似的信号(事件)。第二幅图使用d和d1绘制的子区图形中有一定的随机性(或者噪声),但还是可以和原始(d)信号进行比较。


7.7.4 补充说明
我们也可以为散点图添加直方图,通过这种方式我们能了解更多关于所绘制的数据的信息。我们可以添加水平直方图和垂直直方图来显示在x
轴和y轴上数据点的频率。通过这种方法,我们可以同时看到整个数据集合的汇总信息(直方图)和每一个数据点(散点图)。


下面是一个生成散点—直方图组合的代码示例,该代码使用了本节中提到的两个相同的数据集合。代码的重点是scatterhist()函数,我们可以给它传入不同的数据集合,它使用我们提供的数据集合对一些变量(直方图中bin的数量、坐标轴的范围等)进行设置。


我们从通常的导入开始,代码如下。
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable


下面代码定义了生成散点直方图的函数,给函数一个(x,y)数据集合和一个可选的figsize参数。
def scatterhist(x, y, figsize=(8,8)):
"""
Create simple scatter & histograms of data x, y inside given plot
@param figsize: Figure size to create figure
@type figsize: Tuple of two floats representing size in inches
@param x: X axis data set
@type x: np.array
@param y: Y axis data set
@type y: np.array
"""
_, scatter_axes = plt.subplots(figsize=figsize)
# the scatter plot:
scatter_axes.scatter(x, y, alpha=0.5)
scatter_axes.set_aspect(1.)
divider = make_axes_locatable(scatter_axes)
axes_hist_x = divider.append_axes(position="top", sharex=scatter_
axes,
size=1, pad=0.1)
axes_hist_y = divider.append_axes(position="right",
sharey=scatter_axes,
size=1, pad=0.1)
# compute bins accordingly
binwidth = 0.25
# global max value in both data sets
xymax = np.max([np.max(np.fabs(x)), np.max(np.fabs(y))])
# number of bins
bincap = int(xymax / binwidth) * binwidth
bins = np.arange(-bincap, bincap, binwidth)
nx, binsx, _ = axes_hist_x.hist(x, bins=bins, histtype='stepfilled',
orientation='vertical')
ny, binsy, _ = axes_hist_y.hist(y, bins=bins, histtype='stepfilled',
orientation='horizontal')
tickstep = 50
ticksmax = np.max([np.max(nx), np.max(ny)])
xyticks = np.arange(0, ticksmax + tickstep, tickstep)
# hide x and y ticklabels on histograms
for tl in axes_hist_x.get_xticklabels():
tl.set_visible(False)
axes_hist_x.set_yticks(xyticks)
for tl in axes_hist_y.get_yticklabels():
tl.set_visible(False)
axes_hist_y.set_xticks(xyticks)
plt.show()


现在,加载数据并调用函数来生成并显示图表。
if __name__ == '__main__': # import the data
from ch07_search_data import DATA as d
# Now let's generate random data for the same period
d1 = np.random.random(365)
assert len(d) == len(d1)
# try with the random data
# d = np.random.randn(1000)
# d1 = np.random.randn(1000)
scatterhist(d, d1)


上述代码将生成图7-10所示的图表。



原文网址:        https://www.epubit.com/book/detail/21642
内容来源:异步社区;版权属【人民邮电出版社 异步社区】所有,转载已获得授权;未经授权,不得以任何方式复制和传播本书内容,如需转载请联系异步社区。