I'm trying to use matplotlib to plot binary data read from a file:
import matplotlib.pyplot as plt
try:
f = open(file, 'rb')
data = f.read(100)
plt.plot(data)
except Exception as e:
print(e)
finally:
f.close()
But I got the following error:
'ascii' codec can't decode byte 0xfd in position 0: ordinal not in range(128)
The file I'm reading consists of binary data. So how does matplotlib treat binary data? Is it unsigned or signed 1 byte data?
As has been pointed out in the comments of your question, the bytes you are passing to plot are ambiguous. You need to turn those bytes into a numpy array (or a list/tuple) before passing it to matplotlib.
A simple example to demonstrate this:
import numpy as np
import matplotlib.pyplot as plt
orig_array = np.arange(10, dtype=np.uint8)
with open('my_binary_data.dat', 'wb') as write_fh:
write_fh.write(orig_array)
with open('my_binary_data.dat', 'rb') as fh:
loaded_array = np.frombuffer(fh.read(), dtype=np.uint8)
print loaded_array
plt.plot(loaded_array)
plt.show()
I've gone around the houses in demonstrating using numpy.frombuffer with the bytes you read into your "data" variable, but in truth you would just use numpy.fromfile so that the loading line looks like:
loaded_array = np.fromfile(fh, dtype=np.uint8)
HTH
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With