From: G J. <gle...@gm...> - 2011-04-20 00:31:13
|
As you can see from the error message, it's trying to convert "39.4670," to a float and complaining that this is not a valid value (because of the comma. The examples I suggested were for your original space delimited data. For comma delimited data you'll want to remove the delimiter argument to csv2rec (or explicitly set delimiter=',' if you prefer). If you want to use loadtxt, you can set delimiter=',' Again, read the doc strings to see what these functions are expecting by default. On Tue, Apr 19, 2011 at 5:26 PM, Michael Rawlins <raw...@ya...>wrote: > > The first example produced no plotted symbols but no errors on execution. > The second example produced this: > > Plotting, please wait...maybe more than 10 seconds > > Traceback (most recent call last): > File "testNew.py", line 137, in <module> > data = np.loadtxt('file2.txt') > File "/usr/lib/python2.6/dist-packages/numpy/lib/io.py", line 489, in > loadtxt > X.append(tuple([conv(val) for (conv, val) in zip(converters, vals)])) > ValueError: invalid literal for float(): 39.4670, > > > Grrrr...... > > My code follows. I believe this is standard python and matplotlib. Should > produce a map of Northeast US. Perhaps someone could get this working with > a few example points: > > > 39.4670, -76.1670 > 46.4000, -74.7670 > 45.3830, -75.7170 > 43.6170, -79.3830 > 45.5170, -73.4170 > 45.6170, -74.4170 > 43.8330, -77.1500 > 43.9500, -78.1670 > 43.2500, -79.2170 > 43.8330, -66.0830 > > > #!/usr/bin/env python > # v0.5 19 June 2010 > # General purpose plotter of 2-D gridded data from NetCDF files, > # plotted with map boundaries. > # NetCDF file should have data in either 2-D, 3-D or 4-D arrays. > # Works with the netCDF files in the tutorial, and also the > # files available for download at: > # http://www.cdc.noaa.gov/cdc/data.ncep.reanalysis.html > # Adapted from the basemap example plotmap_pcolor.py, > # Some of the variable names from that example are retained. > # > # Uses basemap's pcolor function. Pcolor accepts arrays > # of the longitude and latitude points of the vertices on the pixels, > # as well as an array with the numerical value in the pixel. > > verbose=0 #verbose=2 says a bit more > > > import sys,getopt > > from mpl_toolkits.basemap import Basemap, shiftgrid, cm > #from netCDF3 import Dataset as NetCDFFile > from mpl_toolkits.basemap import NetCDFFile > from pylab import * > #from matplotlib.mlab import csv2rec > > alloptions, otherargs= getopt.getopt(sys.argv[1:],'ro:p:X:Y:v:t:l:u:n:') # > note the : after o and p > proj='lam' > #plotfile=None > #plotfile='testmap2.png' > usejetrev=False > colorbounds=[None,None] > extratext="" > xvar=None > yvar=None > thevar=None > > therec=None > thelev=None > cbot=None > ctop=None > startlon=-180 #default assumption for starting longitude > for theopt,thearg in alloptions: > print theopt,thearg > if theopt=='-o': # -o needs filename after it, which is now thearg > plotfile=thearg > elif theopt=='-p': > proj=thearg > elif theopt=='-X': > xvar=thearg > elif theopt=='-Y': > yvar=thearg > elif theopt=='-v': > thevar=thearg > elif theopt=='-t': > thetitle=thearg > elif theopt=='-l': > cbot=thearg > elif theopt=='-u': > ctop=thearg > elif theopt=='-n': > therec=thearg > elif theopt=='-m': > thelev=thearg > elif theopt=='-r': > usejetrev=True > else: #something went wrong > print "hmm, what are these??? ", theopt, thearg > sys.exit() > > print "\nPlotting, please wait...maybe more than 10 seconds" > if proj=='lam': #Lambert Conformal > m = > Basemap(llcrnrlon=-80.6,llcrnrlat=38.4,urcrnrlon=-66.0,urcrnrlat=47.7,\ > resolution='l',area_thresh=1000.,projection='lcc',\ > lat_1=65.,lon_0=-73.3) > xtxt=200000. #offset for text > ytxt=200000. > parallels = arange(38.,48.,4.) > meridians = arange(-80.,-68.,4.) > else: #cylindrical is default > # m = > Basemap(llcrnrlon=-180.,llcrnrlat=-90,urcrnrlon=180.,urcrnrlat=90.,\ > # resolution='c',area_thresh=10000.,projection='cyl') > m = > Basemap(llcrnrlon=startlon,llcrnrlat=-90,urcrnrlon=startlon+360.,urcrnrlat=90.,\ > resolution='c',area_thresh=10000.,projection='cyl') > xtxt=1. > ytxt=0. > parallels = arange(-90.,90.,30.) > if startlon==-180: > meridians = arange(-180.,180.,60.) > else: > meridians = arange(0.,360.,60.) > > if verbose>1: print m.__doc__ > xsize = rcParams['figure.figsize'][0] > fig=figure(figsize=(xsize,m.aspect*xsize)) > #ax = fig.add_axes([0.08,0.1,0.7,0.7],axisbg='white') > ax = fig.add_axes([0.06,0.00,0.8,1.0],axisbg='white') > # make a pcolor plot. > #x, y = m(lons, lats) > #p = m.pcolor(x,y,maskdat,shading='flat',cmap=cmap) > #clim(*colorbounds) > > # axes units units are left, bottom, width, height > #cax = axes([0.85, 0.1, 0.05, 0.7]) # colorbar axes for map w/ no > graticule > cax = axes([0.88, 0.1, 0.06, 0.81]) # colorbar axes for map w/ graticule > > axes(ax) # make the original axes current again > > ######### Plot symbol at station locations ################# > > #lines=open('file2.txt','r').readlines() > > #(lats,lons)=([],[]) > #for line in lines: > # (lat,lon)=line.strip().split(',') > # lats.append(float(lat)) > # lons.append(float(lon)) > > #for i in range(len(lons)): > # plt.plot(lats,lons,'*') > > #plt.plot(lons,lats,'*') > > #data = csv2rec('file2.txt',delimiter=',') > > #plot(data[:,0],data[:,1],'o') > > #data = csv2rec('file2.txt',delimiter=' ',names=['lat','lon']) > > #plot(data['lat'],data['lon'],'o') > > data = np.loadtxt('file2.txt') > > plot(data[:,0],data[:,1],'o') > > xpt,ypt = m(-75.0,43.0) > text(xpt,ypt,'*') > > > # draw coastlines and political boundaries. > m.drawcoastlines() > m.drawcountries() > m.drawstates() > # draw parallels and meridians. > # label on left, right and bottom of map. > m.drawparallels(parallels,labels=[1,0,0,0]) > m.drawmeridians(meridians,labels=[1,1,0,1]) > > #if plotfile: > # savefig(plotfile, dpi=72, facecolor='w', bbox_inches='tight', > edgecolor='w', orientation='portrait') > #else: > # show() > > #plt.savefig('map.png') > plt.savefig('map.eps') > # comment show to mass produce > > > > > --- On *Tue, 4/19/11, G Jones <gle...@gm...>* wrote: > > > From: G Jones <gle...@gm...> > > Subject: Re: [Matplotlib-users] plotting points/locations from data file > To: "Michael Rawlins" <raw...@ya...> > Cc: "Ian Bell" <ib...@pu...>, Mat...@li... > Date: Tuesday, April 19, 2011, 8:12 PM > > > No need for a header, but I guess my example was a little too simple. You > could do: > data = csv2rec(filename,delimiter=' ',names=['lat','lon']) > plot(data['lat'],data['lon'],'o') > > or you could do > data = np.loadtxt(filename) > plot(data[:,0],data[:,1],'o') > > In general, I strongly recommend developing with ipython --pylab. That way > all the documentation is at your fingertips using the ? and ?? notation. > > |