0

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

Grayrigel
  • 3,474
  • 5
  • 14
  • 32
  • 2
    So, what is the problem? Also, it helps if you have a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve). – DavidG Jan 03 '18 at 12:07
  • Sorry forgot to mention. I have edited the question and included the error. – Grayrigel Jan 03 '18 at 12:08
  • Can you show an example of what is in the dat files? – DavidG Jan 03 '18 at 12:13
  • Only problem is how do put elements of `data` in the imshow. Examples are given in the questions I have taken inspiration from. They have used random matrices which work fine but I am unsure how to iterate over matrices which I have got from input files. – Grayrigel Jan 03 '18 at 12:16
  • Sure. Here it is. https://pastebin.com/2qFgPVaq. – Grayrigel Jan 03 '18 at 12:19

1 Answers1

1

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]
DavidG
  • 24,279
  • 14
  • 89
  • 82