方块堆叠的频次直方图

# -*- coding: UTF-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()


def make_data(N, f=0.3, rseed=1):
rand = np.random.RandomState(rseed)
x = rand.randn(N)
x[int(f * N):] += 5 # f * N以后全部增加5
return x


x = make_data(1000)
hist = plt.hist(x, bins=30, density=True)
density, bins, patches = hist
print('density:\n ', density)
print('bins:\n ', bins)
print('patches:\n ', patches)
widths = bins[1:] - bins[:-1]
print('(density * widths).sum() is: ', (density * widths).sum())

x2 = make_data(20)
bins = np.linspace(-5, 10, 10)
fig, ax = plt.subplots(1, 2, figsize=(12, 4), sharex=True, sharey=True, subplot_kw={'xlim': (-4, 9), 'ylim': (-0.02, 0.3)})
fig.subplots_adjust(wspace=0.05)
for i, offset in enumerate([0.0, 0.6]):
print('bins + offset:\n', bins + offset)
ax[i].hist(x2, bins=bins + offset, density=True) # 指定bins区间
# np.full_like(): 返回与给定数组具有相同形状和类型的数组。并且数组中元素的值是fill_value的值
ax[i].plot(x2, np.full_like(x2, -0.01), '|k', markeredgewidth=1) # markeredgewidth:竖线条宽度; |k: 黑色竖线
print('x2:\n', x2)

fig2, ax2 = plt.subplots()
bins = np.arange(-3, 8)
ax2.plot(x2, np.full_like(x2, -0.1), '|k', markeredgewidth=1)
for count, edge in zip(*np.histogram(x2, bins)): # 打包把组合里各自元素赋予count和edge
print('np.histogram(x2, bins):\n', np.histogram(x2, bins)) # 返回2个值,第一个是各个区间里的个数,第二个是区间段被刻度值隔出来的刻度值
for i in range(count): # 区间内有几个元素就画几个矩形
ax2.add_patch(plt.Rectangle((edge, i), 1, 1, alpha=0.5)) # 是矩形左下角坐标,宽,高,透明度
ax2.set_xlim(-4, 8)
ax2.set_ylim(-0.2, 8)
plt.show()


留下评论

通过 WordPress.com 设计一个这样的站点
从这里开始