从文件绘制图表

3
我正在尝试使用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

它们似乎都是正确的。感谢大家。 - user3964336
3个回答

1

线索在堆栈跟踪中:

File "pyplot.py", line 2318, in getname_val
name = r.dtype.names[int(identifier)]
IndexError: tuple index out of range

看起来传递的getname_val太短了。查看代码本身:

        elif is_numlike(identifier):
        name = r.dtype.names[int(identifier)]

看起来它正在尝试通过您提供的索引访问名称。这意味着您必须向plotfile提供所有列名。
plt.plotfile('edge_per_one_1.txt', delimiter=' ', cols=(2,4), names=('col1','col2','col3','col4','col5'), marker='o')

简而言之:names参数要求您提供所有列的名称。

1
你在names参数中缺少列名。此外,你的输入文件似乎使用双空格作为分隔符。分隔符应该是单个字符项(空格或逗号)。
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()

0

你也可以使用pyplot提供轴标签:

plt.plotfile('edge_per_one_1.txt', delimiter=' ', cols=(2,4), marker='o')
plt.xlabel("col2")
plt.ylabel("col4")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接