Reputation: 1051
I'm using the following code to try to generate a contour plot using matplotlib.
Script Code:
#!/usr/bin/python
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.colors as colors
import numpy as np
from matplotlib.mlab import griddata
a = np.loadtxt('/home/weather/site_data')
def show_map(self, a):
# 'a' is of the format [(lats, lons, data), (lats, lons, data)... (lats, lons, data)]
lats = [ x[0] for x in a ]
lons = [ x[1] for x in a ]
data = [ x[2] for x in a ]
lat_min = min(lats)
lat_max = max(lats)
lon_min = min(lons)
lon_max = max(lons)
data_min = min(data)
data_max = max(data)
spatial_resolution = 0.5
fig = plt.figure()
x = np.array(lons)
y = np.array(lats)
z = np.array(data)
xinum = (lon_max - lon_min) / spatial_resolution
yinum = (lat_max - lat_min) / spatial_resolution
xi = np.linspace(lon_min, lon_max + spatial_resolution, xinum) # same as [lon_min:spatial_resolution:lon_max] in matlab
yi = np.linspace(lat_min, lat_max + spatial_resolution, yinum) # same as [lat_min:spatial_resolution:lat_max] in matlab
xi, yi = np.meshgrid(xi, yi)
zi = griddata(x, y, z, xi, yi)
m = Basemap(
projection = 'merc',
llcrnrlat=lat_min, urcrnrlat=lat_max,
llcrnrlon=lon_min, urcrnrlon=lon_max,
rsphere=6371200., resolution='l', area_thresh=10000
)
m.drawcoastlines()
m.drawstates()
m.drawcountries()
lat, lon = m.makegrid(zi.shape[1], zi.shape[0])
x,y = m(lat, lon)
m.contourf(x, y, zi)
plt.show()
Data:
[(45.43, -75.65, 75.9), (44.30, -73.63, 85.2), (45.76, -65.76, 68.2)]
I'm trying to figure out if I am inputting the data incorrectly or if there is another underlying issue at hand.
I keep getting the following error code:
ValueError: could not convert string to float: [(45.43,
I tried fixing it myself and thought that I figured it out by removing all parentheses and commas but, then the script didn't even plot an image.
Upvotes: 1
Views: 287
Reputation: 446
I altered your input data file to look like this, which I believe is the format that np.loadtxt()
is looking for
45.43 -75.65 75.9
44.30 -73.63 85.2
45.76 -65.76 68.2
As for why you aren't seeing an image, I removed the self
from your function arguments, and called
show_map(a)
a line before plt.show()
. You never actually call the function show_map()
in your code block, which is why it wasn't executing. I obtain a picture that looks like this:
which may or may not be what you're looking for (I've never used basemap
before). Hope this helps.
Upvotes: 1