I have 4 input data files. I am trying to plot 2D-contour maps using by reading data from these input files with a common colorbar. I have taken inspiration from the following answers :
1) How can I create a standard colorbar for a series of plots in python
2)Matplotlib 2 Subplots, 1 Colorbar
Code :
import numpy as np
import matplotlib.pyplot as plt
#Reading data from input files
dat1 = np.genfromtxt('curmapdown.dat', delimiter=' ')
dat2 = np.genfromtxt('curmapup.dat', delimiter=' ')
dat3 = np.genfromtxt('../../../zika/zika1/CalculateCurvature/curmapdown.dat', delimiter=' ')
dat4 = np.genfromtxt('../../../zika/zika1/CalculateCurvature/curmapup.dat', delimiter=' ')
data=[]
for i in range(1,5):
data.append('dat%d'%i)
fig, axes = plt.subplots(nrows=2, ncols=2)
# Error comes from this part
for ax,dat in zip(axes.flat,data):
im = ax.imshow(dat, vmin=0, vmax=1)
fig.colorbar(im, ax=axes.ravel().tolist())
plt.show()
Error :
Traceback (most recent call last):
File "2dmap.py", line 15, in <module>
im = ax.imshow(dat, vmin=0, vmax=1)
File "/usr/lib/python2.7/dist-packages/matplotlib/__init__.py", line 1814, in inner
return func(ax, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib/axes/_axes.py", line 4947, in imshow
im.set_data(X)
File "/usr/lib/python2.7/dist-packages/matplotlib/image.py", line 449, in set_data
raise TypeError("Image data can not convert to float")
TypeError: Image data can not convert to float
You are appending the string "dat1"
into a list called data
. When plotting this you are trying to convert this string to float, which obviously fails
plt.imshow("hello")
will recreate the error you are seeing.
You want the data itself which you have loaded into variables called dat1
etc. So you would want to remove the first for loop and do something like
data = [dat1, dat2, dat3, dat4]