当我尝试运行以下代码时
import matplotlib.pyplot as plt
import math
import numpy as np
from numpy.random import normal
masses = []
f = open( 'myfile.txt','r')
f.readline()
for line in f:
if line != ' ':
line = line.strip() # Strips end of line character
columns = line.split() # Splits into coloumn
mass = columns[8] # Column which contains mass values
mass = float(mass)
masses.append(mass)
mass = math.log10(mass)
#print(mass)
#gaussian_numbers = #normal(size=1000)
plt.hist(mass, bins = 50, normed = True)
plt.title("Gaussian Histogram")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
我收到此错误
Traceback (most recent call last):
File "C:\Documents and Settings\Khary\My Documents\Python\HALOMASS_READER_PLOTTER.py", line 23, in <module>
plt.hist(mass, bins = 50, normed = True)
File "C:\Python32\lib\site-packages\matplotlib\pyplot.py", line 2191, in hist
ret = ax.hist(x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, **kwargs)
File "C:\Python32\lib\site-packages\matplotlib\axes.py", line 7606, in hist
if isinstance(x, np.ndarray) or not iterable(x[0]):
TypeError: 'float' object is not subscriptable
在做直方图时是否可以不使用浮点数,或者我错过了其他内容?任何和所有的帮助将不胜感激。
答案 0 :(得分:2)
基于the docs,我漂亮确保mass
调用中不属于hist()
...
答案 1 :(得分:0)
@Ignacio诊断正确:你为hist()调用提供了错误的变量。您已经混淆了包含多个浮动质量的列表变量的单例浮点变量质量。 hist()需要一个列表或任何可迭代的Python容器。您可以通过删除一些不需要的东西来改善您的代码并防止混淆。作为一般建议,当使用复数/过去张紧的表格时,使用变量名称是危险的。
import matplotlib.pyplot as plt
mass_list = []
with open('myfile.txt', 'r') as f:
data = [line.strip().split() for line in f.readlines()]
mass_list.extend([float(row[8]) for row in data if row[0] != ''])
plt.hist(mass_list, bins=50, normed=True)
...