Python Forum
Plotting climate data with NetCdf files for a specific region with coordinates
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Plotting climate data with NetCdf files for a specific region with coordinates
#1
I can plot temperature distribution figures with global NetCdf files with these codes.

    import numpy as np
    import matplotlib.pyplot as plt
    from mpl_toolkits.basemap import Basemap
    
    
    from netCDF4 import Dataset as dt
    import numpy as np
    import matplotlib.pyplot as plt 
    
    filestr='E:/VIC/Forcing Data from princeton/from 48 to 2016/01.tmax/tmax_daily_2000-2000.nc'
    
    ncfile=dt(filestr, 'r')
        
    lats = ncfile.variables['lat'][:]
    lons = ncfile.variables['lon'][:]
    time = np.array(ncfile.variables['time'][:], dtype=np.float64)
    data = ncfile.variables['tmax'][300,:,:]
    data -=273
        
    # Set font name
    plt.rcParams["font.family"] = "cambria"
    
        # Add Title
    plt.suptitle('sub title', fontsize=12, fontweight='bold') #<---------
    plt.title('title' , fontsize=12) #<---------
            
        # Add basemap
    map = Basemap(projection='merc',llcrnrlon=30,llcrnrlat=24,urcrnrlon=53,urcrnrlat=43,resolution='i', epsg = 4269) 
            # projection, lat/lon extents and resolution of polygons to draw
            # resolutions: c - crude, l - low, i - intermediate, h - high, f - full
       
        #map.drawmapscale()
    map.arcgisimage(service='World_Physical_Map', xpixels = 5000, verbose= False)
    map.drawcoastlines(linewidth=0.3, color='xkcd:darkblue')
        #map.drawstates(linewidth=0.8)
        #map.drawcountries(color ='r')
        #map.drawlsmask(land_color='Linen', ocean_color='#CCFFFF') # can use HTML names or codes for colors
        #map.drawcounties() # you can even add counties (and other shapefiles!)     
    parallels = np.arange(24.125,42.125,25.) # make latitude lines ever 5 degrees from 30N-50N #<---------
    meridians = np.arange(32.125,52.375,25.) # make longitude lines every 5 degrees from 95W to 70W #<---------
    map.drawparallels(parallels,linewidth=0.3,labels=[1,0,0,0],fontsize=10, color='white')
    map.drawmeridians(meridians,linewidth=0.3,labels=[0,0,0,1],fontsize=10, color='white')
    map.readshapefile('C:/Users/fyunu/OneDrive/Masaüstü/ETB STUDY/Shape File Area of the ETB basin/Aqueduct_river_basins_TIGRIS & EUPHRATES', \
    name='Aqueduct_river_basins_TIGRIS & EUPHRATES', drawbounds=True, linewidth=0.6) #<---------
            
    lon,lat= np.meshgrid(lons,lats)  #(lons-360.,lats) # for this dataset, longitude is 0 through 360, so you need to subtract 180 to properly display on map
    xi,yi = map(lon,lat) #<---------
        
    levels = [i for i in range(-20, 70, 5)] 
        #levels = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.1, 1.5, 2.]
    #levels = [-1., 0.6, 0.80, 0.85, 0.90, 0.95, 1, 1.05, 1.1, 1.15, 1.2, 1.4, 5]
    
        #cs = map.pcolor(xi,yi,var,cmap='jet',vmin=min_value, vmax=max_value) #'RdBu_r')
    map.contour(xi, yi, data, levels, linewidths=0.1, colors='k', linestyles='solid')
    cs = map.contourf(xi, yi, data, levels, cmap=plt.get_cmap('jet'))#cmap=plt.cm.jet) #colors=colors_range) #,vmin=min_value, vmax=max_value) #<---------
            
        # Add Colorbar
    cbar = map.colorbar(cs, location='right', size='5%',pad="1%")
    cbar.set_label('unit') #('Percent’) #<---------
        
    plt.show()
    #plt.savefig(path + 'mapPlot_' + plotInfo.variable + '_' + title + '_' + plotInfo.legend + '.png',transparent=True, dpi=300) #<---------
    plt.close()
    
But I want to select only coordinates of the specific region. I have those coordinates in a csv file. Csv file has one column as 'lons' and one column as 'lats'. I want to read these columns and plot the data distribution according to these coordinates.
I tried
 
        inpExcelFile = 'C:/Users/fyunu/OneDrive/Masaüstü/gridCellCoordinates6 seperately.csv'  #lat, lon
        df1 = pd.read_csv(inpExcelFile) 
        lats = float(df1.columns['lats'][:])  
        lons = float(df1.columns['lons'][:])
        
But I got OSError: Initializing from file failed.
Reply
#2
I suspect it is due to the space in the file name; try removing the space or adding an _ or changing to \\ in the path instead of /
Reply
#3
(Jun-27-2018, 02:03 AM)Maverick494 Wrote: I suspect it is due to the space in the file name; try removing the space or adding an _ or changing to \\ in the path instead of /
I removed that space but still doesn't work.
Reply
#4
maybe it is related and the problem is ü in Masaüstü
https://github.com/pandas-dev/pandas/issues/15086
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sorting data by specific variables using argparse Bearinabox 5 1,369 Jan-01-2023, 07:44 PM
Last Post: Bearinabox
  Training a model to identify specific SMS types and extract relevant data? lord_of_cinder 0 955 Oct-10-2022, 04:35 AM
Last Post: lord_of_cinder
  Binning data to files Kappel 4 2,368 Jun-22-2020, 06:25 PM
Last Post: Kappel
  Plotting a specific bar / rectangle chart? glantz 2 2,145 Apr-30-2020, 11:33 AM
Last Post: glantz
  Ask for machine learning Python example with 2 data files user5566b 2 2,232 Sep-05-2019, 12:15 PM
Last Post: user5566b
  Need Help With Filtering Data For Excel Files Using Pandas eddywinch82 9 5,989 Aug-06-2019, 03:44 PM
Last Post: eddywinch82
  Comparing three functions and plotting specific regions japrap 2 2,185 Aug-06-2019, 12:41 AM
Last Post: japrap
  How to mask the region out side the region of interest Sri 0 1,755 Apr-04-2019, 12:24 PM
Last Post: Sri
  Searching a .txt file for a specific number and extracting the corresponding data nrozman 3 3,179 Jul-27-2018, 02:07 PM
Last Post: nrozman
  How to filter specific rows from large data file Ariane 7 8,143 Jun-29-2018, 02:43 PM
Last Post: gontajones

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020