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?
matplotlibto interpret random binary data? What sort of plot are you looking for?numpy.fromfileto read it into an array.numpy.fromfileis quite handy for what you're describing (There's alsonumpy.fromstringandfrombuffer, if the data isn't in a file). If you want unsigned chars, then dodata = numpy.fromfile(yourfile, dtype=numpy.uint8), if you want signed chars, then dodata = numpy.fromfile(yourfile, dtype=numpy.int8). If you don't want to use numpy have a look at the builtinstructorarraymodules. Either way, if you wantuints, you need to convert the string to a sequence ofuints. Hopefully that helps clarify things a touch.