python Matplotlib 中的直方图与输入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2590328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 01:00:52  来源:igfitidea点击:

Histogram in Matplotlib with input file

pythonmatplotlibhistogram

提问by Arkapravo

I wish to make a Histogram in Matplotlib from an input file containing the raw data (.txt). I am facing issues in referring to the input file. I guess it should be a rather small program. Any Matplotlib gurus, any help ?

我希望从包含原始数据 (.txt) 的输入文件在 Matplotlib 中制作直方图。我在引用输入文件时遇到问题。我想它应该是一个相当小的程序。任何 Matplotlib 大师,有帮助吗?

I am not asking for the code, some inputs should put me on the right way !

我不是要代码,一些输入应该让我走上正确的道路!

回答by doug

i would recommend using 'loadtxt' which is actually in the NumPy library. There are related functions in Matplotlib (csv2rec) but Matplotlib is actually standardizing on loadtxt.

我建议使用实际上在 NumPy 库中的“ loadtxt”。Matplotlib (csv2rec) 中有相关函数,但 Matplotlib 实际上是在 loadtxt 上进行标准化。

Here's how it works:

这是它的工作原理:

from matplotlib import pyplot as PLT

with open('name_of_your_file.csv') as f:
  v = NP.loadtxt(f, delimiter=",", dtype='float', comments="#", skiprows=1, usecols=None)

'v', the object returned from 'loadtxt', is an n x m NumPy array.

'v' 是从 'loadtxt' 返回的对象,是一个 nxm NumPy 数组。

'loadtxt' accepts either a file or a file descriptor. The instance above has most of the method signature. 'skiprows' is an integer that specifies the number of rows counting from the top that you want to skip; it's common to set it to "1" to skip the header row; 'usecols' begins at '0' and is a list reciting the columns you want to include ('None' is the default, and means 'include all'). The other parameters work as expected.

'loadtxt' 接受文件或文件描述符。上面的实例具有大部分方法签名。'skiprows' 是一个整数,指定要跳过的从顶部开始计数的行数;通常将其设置为“1”以跳过标题行;'usecols' 从 '0' 开始,是一个列出您想要包含的列的列表('None' 是默认值,表示'包含所有')。其他参数按预期工作。

To plot a histogram from this data:

要从此数据绘制直方图:

from matplotlib import pyplot as PLT

v_hist = NP.ravel(v)   # 'flatten' v
fig = PLT.figure()
ax1 = fig.add_subplot(111)

n, bins, patches = ax1.hist(v_hist, bins=50, normed=1, facecolor='green')
PLT.show()

回答by Daniel G

You can't directly tell matplotlib to make a histogram from an input file - you'll need to open the file yourself and get the data from it. How you'd do that depends on the format of the file - if it's just a file with a number on each line, you can just go through each line, strip()spaces and newlines, and use float()to convert it to a number.

您不能直接告诉 matplotlib 从输入文件制作直方图 - 您需要自己打开文件并从中获取数据。你怎么做取决于文件的格式——如果它只是一个每行都有一个数字的文件,你可以只浏览每一行、strip()空格和换行符,然后用float()它来将它转换为一个数字。