This page demonstrates Python tips and tricks that I use in my everyday programming as an atmospheric science graduate student.
-Brian Blaylock

Monday, October 10, 2016

Plotting maps with a loop: Best Practices

Best practices for plotting data on a map with a loop...

If you want to plot many data sets with different times on a base map, only plot the base map once!

Some psudo code:

fig = plt.figure(1)
ax  = fig.add_subplot(111)

## Draw Background basemap
m = Basemap(resolution='i',projection='cyl',\
    llcrnrlon=bot_left_lon,llcrnrlat=bot_left_lat,\
    urcrnrlon=top_right_lon,urcrnrlat=top_right_lat,)
m.drawcoastlines()
m.drawcountries()
m.drawcounties()
m.drawstates()

# Brackground image from GIS
m.arcgisimage(service='NatGeo_World_Map', xpixels = 1000, dpi=100)

# Add a shape file for Fire perimiter
p4 = m.readshapefile('/uufs/chpc.utah.edu/common/home/u0553130/fire_shape/perim_'+perimiter,'perim',drawbounds=False)

# Plot station locations
m.scatter(lons,lats)
plt.text(lons[0],lats[0],stnid[0])
plt.text(lons[1],lats[1],stnid[1])

for analysis_h in range(1,5):

    # code to get lat/lon and data

    # plot pcolormesh, and colorbar
    PC = m.pcolormesh(lon,lat,data)
    cbar = plt.colorbar(orientation='horizontal',pad=0.05,shrink=.8,ticks=range(0,80,5))

    # plot contour
    CC = m.contour(lon,lat,data)


    # plot HRRR 10-m winds
    WB = m.barbs(lon,lat,u,v,)
    

    ### Before you plot the next loop, remove the data plots
    cbar.remove()                  # remove colorbar
    PC.remove()                    # remove pcolomesh
    WB[0].remove()              #remove wind barbs
    WB[1].remove()              #   (takes two steps)
    for cc in CC.collections:  #remove each line in the contour collection
        cc.remove()

Thursday, October 6, 2016

Plot NEXRAD Level II Data with MetPy

Plotting NEXRAD Level II data is possible using MetPy.

View my script here: https://github.com/blaylockbk/Ute_other/blob/master/plot_NEXRAD_II_data.py

Example:


Plotting the fire perimeter from a shape file

There is very useful documentation related to plotting shape files on a basemap here: http://basemaptutorial.readthedocs.io/en/latest/shapefile.html

I needed to plot fire perimeter, plotted on this map of Idaho and shaded in red, on a basemap.
This is how I did it...

from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
## My file 
# Plot Fire Perimeter                               
perimiter = '160806'
p4 = m.readshapefile('[PATH]/perim_'+perimiter,'perim',drawbounds=False)
                           
patches   = []
for info, shape in zip(m.perim_info, m.perim):
      if info['FIRENAME'] == 'PIONEER' and info['SHAPENUM']==1772:
             x, y = zip(*shape) 
              #print info
              #m.plot(x, y, marker=None,color='maroon',linewidth=2)
              patches.append(Polygon(np.array(shape), True) )
              ax.add_collection(PatchCollection(patches, facecolor= 'maroon', alpha=.65, edgecolor='k', linewidths=1.5, zorder=1))

Friday, September 23, 2016

Python Matplotlib subscript

This is how to add subscripts to a string in your matlab plot
See more here: http://matplotlib.org/users/mathtext.html

plt.scatter(cyr_no80,co2_no80,color='k',marker='+',label='points')
plt.title(r'CO$_2$ Concentration, no 1980s')
plt.ylabel(r'CO$_2$ (ppm)')
plt.xlabel('Year')


Friday, September 9, 2016

Sorting multiple vectors based on one vector sort order

That title was a mouthful. First, I want to sort an array vector. Then I want to sort other vectors with that same sort order.

I have a vector that contain heights, and with that two other vectors with the corresponding temperature and dew point. I want to sort the height array, and sort the temperature and dew point array in the same manner.

height = np.array([10, 50, 20, 30, 60, 20, 80])
temp = np.array([1, 4, 2, 7, 5, 3, 9])
dwpt = np.array([6, 3, 8, 5, 7, 4, 6])

First, use np.argsort to get the sort order.

sort_order = np.argsort(height)

[out] array([0, 2, 5, 3, 1, 4, 6], dtype=int64)

Now make new arrays of the sorted data with that sort order

sorted_height = np.array(height)[sort_order]
[out] array([10, 20, 20, 30, 50, 60, 80])

sorted_temp = np.array(temp)[sort_order]
[out] array([1, 2, 3, 7, 4, 5, 9])

sorted_dwpt = np.array(dwpt)[sort_order]
[out] array([6, 8, 4, 5, 3, 7, 6])

Thus, you see that we have sorted the height array from lowest to highest, and the temperature and dew point arrays have been sorted, preserving their order with the corresponding height.