类型错误:“浮动”尝试在 matplotlib 中制作直方图时,对象不可下标

发布于 2024-12-14 05:49:53 字数 1367 浏览 0 评论 0原文

当我尝试运行以下代码时

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 

Can one not use floats while getting histograms 或者我错过了其他东西?任何和所有的帮助将不胜感激。

When I try and run the following code

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()

I get this error

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 

Can one not use floats when doing histograms or am I missing something else? Any and all help would be appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

静水深流 2024-12-21 05:49:53

基于文档,我很漂亮< /em> 确定 mass 不属于 hist() 调用...

Based on the docs, I'm pretty sure mass doesn't belong there in the hist() call...

我恋#小黄人 2024-12-21 05:49:53

@Ignacio 诊断正确:您向 hist() 调用提供了错误的变量。您将单例浮点变量 ma​​ss 与包含多个浮点 ma​​ss 的列表变量混淆了。 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)
...

@Ignacio diagnosed it right: you were providing the wrong variable to the hist() call. You had confused the singleton float variable mass for the list variable containing several floats masses. hist() requires a list or any iterable Python container. Your code can be improved by removing some of those things which are not needed and prevent confusion. As a general advice, it's dangerous to use a variable name when the pluralized/past-tensed forms are also used.

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)
...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文