【问题标题】:Parse data from external file for matplotlib bar chart从外部文件解析数据以获取 matplotlib 条形图
【发布时间】:2013-09-27 16:37:33
【问题描述】:

我想从一个包含两列的文本文件中读取数据。这是对先前提出的问题Generating a matlibplot bar chart from two columns of data 的跟进。虽然我的问题类似于How to plot data from multiple two column text files with legends in Matplotlib?,但我无法让我定义的变量与条形图一起使用。目标是从包含两列的文件中读取数据。

我首先尝试使用在当前代码中被注释掉的genfromtxt,但收到AttributeError: 'numpy.ndarray' object has no attribute 'split'。这可能是由于以数组类型格式读取的数据:

>>> import numpy as np
>>> data = np.genfromtxt('input-file', delimiter = ' ')
>>> print(data)
[[ 72.   1.]
 [  9.   2.]
 [ 10.  36.]
 [ 74.   6.]
 [  0.  77.]
 [  5.   6.]
 [  6.  23.]
 [ 72.   1.]
 [  9.   2.]
 [ 10.  36.]
 [ 82.   1.]
 [ 74.   6.]
 [  0.  97.]
 [  5.   6.]
 [  6.  23.]
 [ 72.   1.]
 [  9.   2.]
 [ 10.  36.]
 [ 82.   1.]]

接下来,我尝试直接读取数据但收到AttributeError: 'file' object has no attribute 'split'

import numpy as np
import matplotlib.pyplot as plt

data = open('input-file', 'r')

#data = np.genfromtxt('input-file', delimiter = ' ')

counts = []
values = []

for line in data.split("\n"):
    x, y = line.split()
    values.append(int(x))
    counts.append(int(y))

#bar_width = 0.25
#opacity = 0.4

plt.bar(values, counts, color='g')
plt.ylabel('Frequency')
plt.xlabel('Length')
plt.title('Title')

plt.show()

来自input-file的示例内容。

72 1
9 2
10 36
74 6
0 77
5 6
6 23
72 1
9 2
10 36
82 1
74 6
0 97
5 6
6 23
72 1
9 2
10 36
82 1

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    文件对象没有拆分功能。不用split("\n")也可以直接读行

    for line in data:
    

    【讨论】:

      【解决方案2】:

      是什么阻止您直接绘制从np.genfromtext 返回的 numpy 数组的列?

      data = np.genfromtxt('tmp.dat', delimiter = ' ')
      
      plt.bar(data[:,0], data[:,1], color='g')
      plt.ylabel('Frequency')
      plt.xlabel('Length')
      plt.title('Title')
      
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 2020-12-03
        • 2015-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-03
        相关资源
        最近更新 更多