I would like to read data from a text file which has two columns. This is a follow-up to a previously asked question Generating a matlibplot bar chart from two columns of data. While my question is similar to How to plot data from multiple two column text files with legends in Matplotlib?, I am unable to get my defined variables to work with a bar chart. The goal is to read data in from a file which contains two columns.
I first tried using genfromtxt
which is commented out in the current code, but receive AttributeError: 'numpy.ndarray' object has no attribute 'split'
. This is likely due to the data being read in an array type format:
>>> 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.]]
Next, I trid read data in directly but receive 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()
Example contents from 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