欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

AttributeError: module 'matplotlib.mlab' has no attribute 'normpdf'

程序员文章站 2022-03-18 21:37:16
...

AttributeError: module ‘matplotlib.mlab’ has no attribute ‘normpdf’

在练习直方图时报错:

Traceback (most recent call last):

  File "F:\Studing\Python\Anaconda\未命名0.py", line 20, in <module>
    y = mlab.normpdf(bins,mu,sigma)

AttributeError: module 'matplotlib.mlab' has no attribute 'normpdf'

源代码:(基于Python的大数据分析基础及实战一书P188)

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

mu = 100
sigma = 15
x = mu + sigma * np.random.randn(10000)
print("x:",x.shape)
num_bins = 50
n, bins, patches = plt.hist(x,num_bins,normed=1,facecolor='green',alpha=0.5)

y = mlab.normpdf(bins,mu,sigma)

plt.plot(bins,y,'r--')
plt.xlabel('Smarts')
plt.ylabel('Prbability')

plt.title('Histogram of IQ:$\mu=100$,$\sigma=15$')

plt.subplots_adjust(left=0.15)
plt.show()
print("bind:\n",bins)

主要是在y = mlab.normpdf(bins,mu,sigma)这句,mlab中没有了normpdf;经百度找到替代方法,使用scipy.stats.norm.pdf以完成绘制:
修改后代码:

import numpy as np
from scipy import stats  #此处新增
import matplotlib.pyplot as plt

mu = 100
sigma = 15
x = mu + sigma * np.random.randn(10000)
print("x:",x.shape)
num_bins = 50
n, bins, patches = plt.hist(x,num_bins,normed=1,facecolor='green',alpha=0.5)

y = stats.norm.pdf(bins,mu,sigma) #此处有修改

plt.plot(bins,y,'r--')
plt.xlabel('Smarts')
plt.ylabel('Prbability')

plt.title('Histogram of IQ:$\mu=100$,$\sigma=15$')

plt.subplots_adjust(left=0.15)
plt.show()
print("bind:\n",bins)

本文链接:https://editor.csdn.net/md?articleId=105952579

参考文章:https://blog.csdn.net/salmonwilliam/article/details/103365244

相关标签: Python