hor*_*uzz 1 python animation matplotlib histogram
我有以下动画子图模拟四种不同分布的直方图:
import numpy
from matplotlib.pylab import *
import matplotlib.animation as animation
n = 100
# generate 4 random variables from the random, gamma, exponential, and uniform distributions
x1 = np.random.normal(-2.5, 1, 10000)
x2 = np.random.gamma(2, 1.5, 10000)
x3 = np.random.exponential(2, 10000)+7
x4 = np.random.uniform(14,20, 10000)
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
def updateData(curr):
if curr == n:
a.event_source.stop()
ax1.hist(x1[:curr], normed=True, bins=20, alpha=0.5)
ax2.hist(x2[:curr], normed=True, bins=20, alpha=0.5)
ax3.hist(x3[:curr], normed=True, bins=20, alpha=0.5)
ax4.hist(x4[:curr], normed=True, bins=20, alpha=0.5)
simulation = animation.FuncAnimation(fig, updateData, interval=20, repeat=False)
plt.show()
Run Code Online (Sandbox Code Playgroud)
它有效,但由于某种原因,y 轴缩放忽略了 normed=True。如果我从动画中取出这些图,它们会正确缩放。如何在动画中获得适当的缩放?
编辑
normed = True
直方图的参数使直方图绘制分布的密度。从文档:
normed : 布尔值,可选
如果为 True,则返回元组的第一个元素将是归一化以形成概率密度的计数,即 n/(len(x)`dbin),即直方图的积分总和为 1 . 如果 stack 也是 True,则直方图的总和被归一化为 1。默认为 False
这意味着直方图条的高度取决于 bin 宽度。如果只绘制一个数据点,就像动画开始时的情况一样,条形高度将为 1./binwidth。如果 bin 宽度小于零,则条形高度可能会变得非常大。
因此,修复垃圾箱并在整个动画中使用它们是个好主意。
清除轴也是合理的,这样就不会绘制 100 个不同的直方图。
import numpy as np
from matplotlib.pylab import *
import matplotlib.animation as animation
# generate 4 random variables from the random, gamma, exponential, and uniform distribution
x1 = np.random.normal(-2.5, 1, 10000)
x2 = np.random.gamma(2, 1.5, 10000)
x3 = np.random.exponential(2, 10000)+7
x4 = np.random.uniform(14,20, 10000)
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
def updateData(curr):
if curr <=2: return
for ax in (ax1, ax2, ax3, ax4):
ax.clear()
ax1.hist(x1[:curr], normed=True, bins=np.linspace(-6,1, num=21), alpha=0.5)
ax2.hist(x2[:curr], normed=True, bins=np.linspace(0,15,num=21), alpha=0.5)
ax3.hist(x3[:curr], normed=True, bins=np.linspace(7,20,num=21), alpha=0.5)
ax4.hist(x4[:curr], normed=True, bins=np.linspace(14,20,num=21), alpha=0.5)
simulation = animation.FuncAnimation(fig, updateData, interval=50, repeat=False)
plt.show()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4228 次 |
最近记录: |