我正在尝试使用 matplotlib 在 python 中绘制图形。我试图作为输入提供的文件是没有分隔符的 txt 文件。它有很多列,我对 col[2]
和 col[4]
很感兴趣。数据可以是 str 或 int 或 float
。
输入文件
3401 1772 1 0.0002 3498.0
3840 3730 5 0.001 4658.0
3439 651 13 0.0026 22208.0
5069 3354 2 0.0004 3510.0
5252 4001 5 0.001 3468.0
5417 2970 5 0.001 4224.0
4653 3928 5 0.001 10132.0
1681 1028 2 0.0004 9399.0
2908 2615 4 0.0008 19306.0
代码:
import numpy as np
import matplotlib.pyplot as plt
from pylab import*
import math
from matplotlib.ticker import LogLocator
plt.plotfile('edge_per_one_1.txt', delimiter=' ', cols=(2,4), names=('col2','col4'), marker='o')
plt.show()
错误:
Traceback (most recent call last):
File "plot_data.py", line 7, in <module>
plt.plotfile('edge_per_one_1.txt', delimiter=' ', cols=(2,4), names=('col2','col4'), marker='o')
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 1894, in plotfile
xname, x = getname_val(cols[0])
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 1889, in getname_val
name = r.dtype.names[int(identifier)]
IndexError: tuple index out of range
最佳答案
您在 names
参数中遗漏了列名。此外,您的输入文件似乎有双空格作为分隔符。分隔符应该是 SINGLE CHAR 项(空格或逗号)。
import matplotlib.pyplot as plt
plt.plotfile('edge_per_one_1.txt', delimiter=' ', cols=(2,4),
names=('col1','col2','col3','col4','col5'), marker='o')
plt.show()
关于python - 从文件中绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25665285/