AttributeError:模块“matplotlib.pyplot”没有属性“pyplot”

2024-09-25 08:41:35 发布

您现在位置:Python中文网/ 问答频道 /正文

在写这个问题的时候解决了它,把它留给像我这样有麻烦的白痴

我最近通过一些教程开始用python编写代码,但无法使用matplotlib

设置:

  • VS代码,无虚拟环境
  • Anaconda 3(据我所知,matplotlib应该可以工作)

错误:

我在运行代码时遇到以下错误:

> PS C:\Users\USER\Desktop\Python Course> python Testing.py
Traceback (most recent call last):
  File "Testing.py", line 66, in <module>
    plt.pyplot.hist(dataset["horsepower"])
AttributeError: module 'matplotlib.pyplot' has no attribute 'pyplot'

措施:

  • 我尝试过将pyplot作为from matplotlib import pyplot as pltimport matplotlib.pyplot as plt导入,也尝试过先导入matplotlib,然后导入pyplot而没有效果

  • pip install --upgrade matplotlib(已经安装了,但只是为了确保安全)

  • “升级”matplotlib后,无法使用matplotlib.__version__检查matplotlib版本,因此我输入了pip list,在那里我发现了matplotlib 3.2.1,让我相信这不是安装错误

  • 最后,我在D:\Anaconda3\Lib\site-packages中创建了一个名为example.pth的.pth文件,其中只包含以下内容:

C:\Users\USER\AppData\Roaming\Python\Python37\Scripts

对于这个问题,我已经讨论了所有类似的问题,但我无法理解。如此之多,以至于我最终为此创建了一个如此之多的帐户

示例代码:

import pandas as pd 
import numpy as np
from matplotlib import pyplot as plt

#importing dataset csv
path = "C:\\Users\\USER\\Desktop\\Python Course\\vehicle.data"
dataset=pd.read_csv(path, header=None)

#assigning non-existant headers
headers = ["symboling","normalized-losses","make","fuel-type","aspiration", "num-of-doors","body-style",
         "drive-wheels","engine-location","wheel-base", "length","width","height","curb-weight","engine-type",
         "num-of-cylinders", "engine-size","fuel-system","bore","stroke","compression-ratio","horsepower",
         "peak-rpm","city-mpg","highway-mpg","price"]
dataset.columns = headers

#eliminates cars with no price recording
dataset.dropna(subset=["price"], axis=0)

dataset[['length','compression-ratio'] ].describe()

#converting to km
dataset["city-mpg"]=235/dataset["city-mpg"]
dataset.rename(columns={"city-mpg": "city-L/100Km"}, inplace=True)
dataset["highway-mpg"]=235/dataset["highway-mpg"]
dataset.rename(columns={"highway-mpg": "highway-L/100Km"}, inplace=True)

#standarizing missing values to NaN (python default)
dataset.replace("?", np.nan, inplace = True)
missing_data = dataset.isnull() #(False=not missing value, true=missing value)


#Replacing normalized-loss
avg_normloss=dataset["normalized-losses"].astype("float").mean(axis=0) #122.0
dataset["normalized-losses"].replace(np.nan, avg_normloss, inplace=True)
#stroke
avg_stroke=dataset["stroke"].astype("float").mean(axis=0) #122.0
dataset["stroke"].replace(np.nan, avg_stroke, inplace=True)
#bore
avg_bore=dataset["bore"].astype("float").mean(axis=0) #122.0
dataset["bore"].replace(np.nan, avg_bore, inplace=True)
#horsepower
avg_HP=dataset["horsepower"].astype("float").mean(axis=0) #122.0
dataset["horsepower"].replace(np.nan, avg_HP, inplace=True)
#peak-rpm
avg_peak=dataset["peak-rpm"].astype("float").mean(axis=0) #122.0
dataset["peak-rpm"].replace(np.nan, avg_peak, inplace=True)
#num-of-doors
freq_doors=dataset['num-of-doors'].value_counts().idxmax()
dataset["num-of-doors"].replace(np.nan, freq_doors, inplace=True)
#Dropping rows with no price
dataset.dropna(subset=["price"],axis=0,inplace=True)
#reset index
dataset.reset_index(drop=True, inplace=True)

#data types corrections
dataset[["bore", "stroke", "price", "peak-rpm"]] = dataset[["bore", "stroke", "price", "peak-rpm"]].astype("float")
dataset[["normalized-losses", "horsepower"]] = dataset[["normalized-losses", "horsepower"]].astype("int")

#normalization
#0 to 1 values
dataset['length'] = dataset['length']/dataset['length'].max()
dataset['width'] = dataset['width']/dataset['width'].max()
dataset['height'] = dataset['height']/dataset['height'].max()

#HP histrogram
plt.pyplot.hist(dataset["horsepower"])
plt.pyplot.xlabel("horsepower")
plt.pyplot.ylabel("count")
plt.pyplot.title("horsepower bins")

bins = np.linspace(min(dataset["horsepower"]), max(dataset["horsepower"]), 4)
group_names = ['Low', 'Medium', 'High']
dataset.to_csv("vehicledata.csv", index=False)

代码中引用的文件位于此处:File

已解决plt.pyplot.hist(dataset["horsepower"])和随后的3行代码是错误的。写plt.pyplot.hist()是多余的,就我而言,这并不明显是错误的。将调用更改为plt.hist()修复了我的问题


Tags: truestrokematplotlibnppltpricedatasetavg