import numpy as np
import xarray as xr
import cartopy.feature as cfeature
import cartopy.crs as ccrs
import matplotlib.pyplot as plt

import geocat.datafiles as gdf
from geocat.viz import cmaps as gvcmaps
from geocat.viz import util as gvutil

###############################################################################
# Read in data:

# Open a netCDF data file using xarray default engine and load the data into xarrays
ds = xr.open_dataset(gdf.get("netcdf_files/h_avg_Y0191_D000.00.nc"), decode_times=False)
# print(ds)
# Extract a slice of the data
t = ds.T.isel(time=0, z_t=0).sel(lat_t=slice(-60, 30), lon_t=slice(30, 120))

###############################################################################
# Plot:

fig = plt.figure(figsize=(12, 12))


def Plot(color, row, col, pos, title):

    # Generate axes, using Cartopy, drawing coastlines, and adding features
    projection = ccrs.PlateCarree()
    ax1 = plt.subplot(row, col, pos, projection=projection)
Example #2
0
import numpy as np
import xarray as xr
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt

import geocat.datafiles as gdf
from geocat.viz import cmaps as gvcmaps
from geocat.viz import util as gvutil

###############################################################################
# Read in data:

# Open a netCDF data file using xarray default engine and load the data into xarrays
ds = xr.open_dataset(gdf.get("netcdf_files/atmos.nc"), decode_times=False)

# Extract variable
v = ds.PBLH.isel(time=0)

# Fix the artifact of not-shown-data around 0 and 360-degree longitudes
t = gvutil.xr_add_cyclic_longitudes(v, "lon")

###############################################################################
#Plot:

fig = plt.figure(figsize=(12, 12))


def Plot(color, row, col, pos, title):
Example #3
0
# Import packages:

import numpy as np
import matplotlib.pyplot as plt
import xarray as xr
import cartopy.crs as ccrs

import geocat.datafiles as gdf
from geocat.viz import cmaps as gvcmaps
import geocat.viz.util as gvutil

###############################################################################
# Read in data:

# Open a netCDF data file using xarray default engine and load the data into xarray
ds = xr.open_dataset(gdf.get("netcdf_files/uv300.nc")).isel(time=1)

###############################################################################
# Plot:

# Generate figure and set its size in (width, height)
fig = plt.figure(figsize=(10, 8))

# Generate axes using Cartopy to draw coastlines
ax = plt.axes(projection=ccrs.PlateCarree())
ax.coastlines(linewidth=0.5, alpha=0.6)

# Use geocat.viz.util convenience function to set axes limits & tick values
gvutil.set_axes_limits_and_ticks(ax,
                                 xlim=(-180, 180),
                                 ylim=(-90, 90),
################################################################################
# Import packages:
import numpy as np
import xarray as xr

import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter

import geocat.datafiles as gdf
from geocat.viz import util as gvutil

###############################################################################
# Read in data:

# Open a netCDF data file using xarray default engine and load the data into xarrays
ds = xr.open_dataset(gdf.get("netcdf_files/mxclim.nc"))
# Extract variables
U = ds.U[0, :, :]
V = ds.V[0, :, :]

################################################################################
# Plot:

# Generate figure (set its size (width, height) in inches) and axes
plt.figure(figsize=(12, 12))
ax = plt.gca()

# Set y-axis to have log-scale
plt.yscale('log')

# Contour-plot U-data
Example #5
0
import numpy as np
import xarray as xr
import cartopy.feature as cfeature
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.ticker as mticker

import geocat.datafiles as gdf
from geocat.viz import util as gvutil

###############################################################################
# Read in data:

# Open a netCDF data file using xarray default engine and load the data into xarrays
ds = xr.open_dataset(gdf.get("netcdf_files/uv300.nc"))
U = ds.U[1, :, :]

###############################################################################
# Fix the artifact of not-shown-data around 0 and 360-degree longitudes
wrap_U = gvutil.xr_add_cyclic_longitudes(U, "lon")

###############################################################################
# Plot:

# Generate axes, using Cartopy, drawing coastlines, and adding features
fig = plt.figure(figsize=(10, 10))
projection = ccrs.NorthPolarStereo()
ax = plt.axes(projection=projection)
ax.add_feature(cfeature.LAND, facecolor='lightgray')
import xarray as xr
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.colors as mcolors

import geocat.datafiles as gdf
from geocat.viz import cmaps as gvcmaps

###############################################################################
# Read in data:

# Open a netCDF data file using xarray default engine and load the data into xarrays
uf = xr.open_dataset(gdf.get("netcdf_files/Ustorm.cdf"))
vf = xr.open_dataset(gdf.get("netcdf_files/Vstorm.cdf"))
pf = xr.open_dataset(gdf.get("netcdf_files/Pstorm.cdf"))
tf = xr.open_dataset(gdf.get("netcdf_files/Tstorm.cdf"))
u500f = xr.open_dataset(gdf.get("netcdf_files/U500storm.cdf"))
v500f = xr.open_dataset(gdf.get("netcdf_files/V500storm.cdf"))

p = pf.p.isel(timestep=0).drop('timestep')
t = tf.t.isel(timestep=0).drop('timestep')
u = uf.u.isel(timestep=0).drop('timestep')
v = vf.v.isel(timestep=0).drop('timestep')
u500 = u500f.u.isel(timestep=0).drop('timestep')
v500 = v500f.v.isel(timestep=0).drop('timestep')
time = vf.timestep

# Convert Pa to hPa
Example #7
0
# Import packages

from netCDF4 import Dataset
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import cartopy.crs as ccrs
from cartopy.feature import NaturalEarthFeature

from wrf import (getvar, to_np, latlon_coords, get_cartopy)
import geocat.datafiles as gdf

###############################################################################
# Read in the data

wrfin = Dataset(gdf.get("netcdf_files/wrfout_d03_2012-04-22_23_00_00_subset.nc"))
td2 = getvar(wrfin, "td2")

# Set attributes for creating plot titles later
we = getattr(wrfin, 'WEST-EAST_GRID_DIMENSION')
sn = getattr(wrfin, 'SOUTH-NORTH_GRID_DIMENSION')
lvl = getattr(wrfin, 'BOTTOM-TOP_GRID_DIMENSION')
dis = getattr(wrfin, 'DY')/1000 # Divide by 1000 to go from m to km
phys = getattr(wrfin,'MP_PHYSICS')
pbl = getattr(wrfin, 'BL_PBL_PHYSICS')
cu = getattr(wrfin, 'CU_PHYSICS')
s_date = getattr(wrfin, 'START_DATE') 
str_format = "WE={}; SN={}; Levels={}; Dis={}km; Phys Opt={}; PBL Opt={}; Cu Opt={}"
sd_frmt = "Init: {}"

###############################################################################
import geocat.datafiles as gdf

###############################################################################
# A utility function

# Define a utility function that handles the no-shown-data artifact of 0 and 360-degree longitudes
def xr_add_cyclic(da, coord):
    cyclic_data, cyclic_coord = cutil.add_cyclic_point(da.values, coord=da[coord])

    coords = da.coords.to_dataset()
    coords[coord] = cyclic_coord
    return xr.DataArray(cyclic_data, dims=da.dims, coords=coords.coords)

###############################################################################
# Open a netCDF data file using xarray default engine and load the data into xarrays
ds = xr.open_dataset(gdf.get("netcdf_files/b003_TS_200-299.nc"), decode_times=False)
x = ds.TS

# Apply mean reduction from coordinates as performed in NCL's dim_rmvmean_n_Wrap(x,0)
# Apply this only to x.isel(time=0) because NCL plot plots only for time=0
newx = x.mean('time')
newx = x.isel(time=0) - newx

# Resolve the no-shown-data artifact of 0 and 360-degree longitudes
newx = xr_add_cyclic(newx, "lon")

###############################################################################
# Plot

# First get axes for a projection of preference
fig = plt.figure()
Example #9
0
#Lily's version of the NCL example bar_4.ncl
#This is a work in progress

#import packages
import numpy as np
import xarray as xr

import matplotlib.pyplot as plt

import geocat.datafiles as gdf

#read data file
dataf = xr.open_dataset(gdf.get('netcdf_files/SOI.nc'), decode_times=False)

data = dataf.SOI_SIGNAL[0:dataf.time.size]

#print(dataf)

#print(data)


def bar_color(df, color1, color2):
    return np.where(df.values > 0, color1, color2).T


fig = plt.figure(figsize=(5, 5))
ax = plt.gca()

colorlist = ['red', 'orange', 'yellow', 'green', 'blue', 'navyblue', 'purple']
x = dataf.yyyymm[:] / 100.0
Example #10
0
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon
import matplotlib.colors as colors
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import matplotlib.cm as cm
import shapefile as shp
import numpy as np

import geocat.datafiles as gdf
from geocat.viz import util as gvutil

###############################################################################
# Read in data:

# Open all shapefiles and associated .dbf, .shp, and .prj files so sphinx can run and generate documents
file1 = open(gdf.get("shape_files/gadm36_USA_1.dbf"), 'r')
file2 = open(gdf.get("shape_files/gadm36_USA_1.shp"), 'r')
file3 = open(gdf.get("shape_files/gadm36_USA_1.shx"), 'r')
file4 = open(gdf.get("shape_files/gadm36_USA_1.prj"), 'r')

file5 = open(gdf.get("shape_files/gadm36_USA_2.dbf"), 'r')
file6 = open(gdf.get("shape_files/gadm36_USA_2.shp"), 'r')
file7 = open(gdf.get("shape_files/gadm36_USA_2.shx"), 'r')
file8 = open(gdf.get("shape_files/gadm36_USA_2.prj"), 'r')

file9 = open(gdf.get("shape_files/gadm36_PRI_0.dbf"), 'r')
file10 = open(gdf.get("shape_files/gadm36_PRI_0.shp"), 'r')
file11 = open(gdf.get("shape_files/gadm36_PRI_0.shx"), 'r')
file12 = open(gdf.get("shape_files/gadm36_PRI_0.prj"), 'r')

# Open the text file with the population data
Example #11
0
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cm
from geocat.viz import util as gvutil

import geocat.datafiles as gdf
import cartopy.io.shapereader as shpreader
import shapely.geometry as sgeom
from mpl_toolkits.axes_grid1.inset_locator import inset_axes

###############################################################################
# Read in data

# Open climate division datafile and add to xarray
ds = xr.open_dataset(gdf.get("netcdf_files/climdiv_prcp_1899-1999.nc"), decode_times=False)

###############################################################################
# Initialize color map and bounds for each color

colormap = colors.ListedColormap(['mediumpurple', 'mediumblue', 'royalblue', 'cornflowerblue', 'lightblue', 'lightseagreen', 'yellowgreen',
                                  'green', 'wheat', 'tan', 'gold', 'orange', 'red', 'firebrick'])

# Values represent average number of inches of rain
colorbounds = [0, 5, 10, 15, 20, 25, 30, 35, 40, 50, 60, 70, 80, 90, 100]

###############################################################################
# Define helper function to determine which color to fill the divisions based on precipitation data

def findDivColor(colorbounds, pdata):
Example #12
0
from netCDF4 import Dataset
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from wrf import (getvar, to_np, latlon_coords, get_cartopy)

import geocat.datafiles as gdf
from geocat.viz import util as gvutil

###############################################################################
# Read in the data

wrfin = Dataset(gdf.get("netcdf_files/wrfout_d01_2003-07-15_00_00_00"), decode_times=True)

q2 = getvar(wrfin, "Q2")

###############################################################################
# Plot the data

lats, lons = latlon_coords(q2)

# The `get_cartopy` wrf function will automatically find and use the 
# intended map projection for this dataset 
cart_proj = get_cartopy(q2)
fig = plt.figure(figsize=(10,10))
ax = plt.axes(projection=cart_proj)

# Add features to the map
Example #13
0
###############################################################################
# Import packages:

import numpy as np
import xarray as xr
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker

import geocat.datafiles as gdf

###############################################################################
# Read in data:

# Open a netCDF data file using xarray default engine and load the data into xarrays
ds = xr.open_dataset(gdf.get("netcdf_files/pre.8912.mon.nc"),
                     decode_times=False)

# Extract a slice of the data
t = ds.pre.isel(time=0)

###############################################################################
# Plot:

plt.figure(figsize=(14, 14))


def Plot(row, col, pos, proj, title):
    '''
    Args:
        
Example #14
0
# Import packages:
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr

import geocat.datafiles as gdf
from geocat.viz import cmaps as gvcmaps
from geocat.viz import util as gvutil

###############################################################################
# Read in data:

# Open a netCDF data file using xarray default engine and load the data into xarrays
ds = xr.open_dataset(
    gdf.get("netcdf_files/atmos.nc"), decode_times=False
)  # Disable time decoding due to missing necessary metadata
# Extract a slice of the data
ds = ds.isel(time=0).drop("time")

###############################################################################
# Data Masking:

# Use xarray.DataArray.where() function to mask out land and then ocean data
land_only = ds.TS.where(ds.ORO == 1.0)
ocean_only = ds.TS.where(ds.ORO == 0.0)
land_only = gvutil.xr_add_cyclic_longitudes(land_only, "lon")
ocean_only = gvutil.xr_add_cyclic_longitudes(ocean_only, "lon")

###############################################################################
# Plot Ocean Only:
Example #15
0
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cm
from geocat.viz import util as gvutil

import geocat.datafiles as gdf
import cartopy.io.shapereader as shpreader
import shapely.geometry as sgeom
from mpl_toolkits.axes_grid1.inset_locator import inset_axes

###############################################################################
# Read in data

# Open climate division datafile and add to xarray
ds = xr.open_dataset(gdf.get("netcdf_files/climdiv_prcp_1899-1999.nc"),
                     decode_times=False)

###############################################################################
# Initialize color map and bounds for each color

colormap = colors.ListedColormap([
    'mediumpurple', 'mediumblue', 'royalblue', 'cornflowerblue', 'lightblue',
    'lightseagreen', 'yellowgreen', 'green', 'wheat', 'tan', 'gold', 'orange',
    'red', 'firebrick'
])

# Values represent average number of inches of rain
colorbounds = [0, 5, 10, 15, 20, 25, 30, 35, 40, 50, 60, 70, 80, 90, 100]

###############################################################################
# Import packages:
import numpy as np
import xarray as xr
import cartopy.crs as ccrs

import matplotlib.pyplot as plt

import geocat.datafiles as gdf
from geocat.viz import cmaps as gvcmaps
from geocat.viz import util as gvutil

###############################################################################
# Read in data:

# Open a netCDF data file using xarray default engine and load the data into xarrays
ds = xr.open_dataset(gdf.get('netcdf_files/uv300.nc'))
U = ds.U[1,:,:]

###############################################################################
# Plot:

# Generate figure (set its size (width, height) in inches)
plt.figure(figsize=(14, 7))

# Generate axes, using Cartopy
projection = ccrs.PlateCarree()
ax = plt.axes(projection=projection)

# Use global map and draw coastlines
ax.set_global()
ax.coastlines()
Example #17
0
"""

###############################################################################
# Import packages:
import numpy as np
import xarray as xr
import matplotlib.pyplot as plt

import geocat.datafiles as gdf
from geocat.viz import util as gvutil

###############################################################################
# Read in data:

# Open a netCDF data file using xarray default engine and load the data into xarrays
ds = xr.open_dataset(gdf.get("netcdf_files/soi.nc"))
dsoik = ds.DSOI_KET
date = ds.date
num_months = np.shape(date)[0]

# Dates in the file are represented by year and month (YYYYMM)
# representing them fractionally will make ploting the data easier
# This produces the same results as NCL's yyyymm_to_yyyyfrac() function
date_frac = np.empty_like(date)
for n in np.arange(0, num_months, 1):
    yyyy = int(date[n] / 100)
    mon = (date[n] / 100 - yyyy) * 100
    date_frac[n] = yyyy + (mon - 1) / 12

###############################################################################
# Plot
Example #18
0
# Import packages
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt

from cartopy.mpl.ticker import LatitudeFormatter

import geocat.datafiles as gdf
from geocat.viz import cmaps as gvcmaps
from geocat.viz import util as gvutil

###############################################################################
# Read in our data

# Open a netCDF data file using xarray default engine and load the data into xarrays
ds = xr.open_dataset(gdf.get('netcdf_files/b003_TS_200-299.nc'),
                     decode_times=False)
ts = ds.TS[:, :, 29]

###############################################################################
# Create our plot

# Import an NCL colormap
palette = gvcmaps.ViBlGrWhYeOrRe

# Generate figure (set its size (width, height) in inches)
fig = plt.figure(figsize=(7, 7))

# Create axes
ax = plt.axes()
Example #19
0
import geocat.viz.util as gvutil

import numpy as np
import xarray as xr
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
from matplotlib import cm
from cartopy.mpl.geoaxes import GeoAxes
from mpl_toolkits.axes_grid1 import AxesGrid

###############################################################################
# Read in data:

# Open a netCDF data file (Sea surface temperature) using xarray default
# engine and load the data into xarrays
ds = xr.open_dataset(gdf.get('netcdf_files/sst.nc'))
sst = ds.TEMP[0, 0, :, :]
lat = ds.LAT[:]
lon = ds.LON[:]

###############################################################################
# Invoke geocat.comp.linint2_points():

# Provide (output) interpolation locations. This script uses 3000 arbitrary locations world-wide in order to demonstrate
# an extensive comparison of the linint2_points outputs to the original grid throughout the globe. The function can be
# even used for a single location though.
newlat = np.random.uniform(low=min(lat), high=max(lat), size=(3000, ))
newlon = np.random.uniform(low=min(lon), high=max(lon), size=(3000, ))

# Call `linint2_points` from `geocat-comp`
newsst = geocat.comp.linint2_points(sst, newlon, newlat, False)
Example #20
0
colormap = colors.ListedColormap([
    'darkblue', 'mediumblue', 'blue', 'cornflowerblue', 'skyblue',
    'aquamarine', 'lime', 'greenyellow', 'gold', 'orange', 'orangered', 'red',
    'maroon'
])

colorbounds = np.arange(0, 56, 4)

norm = mcolors.BoundaryNorm(colorbounds, colormap.N)

################################################################################
# Read in data:

# Open a netCDF data file using xarray default engine and load the data into xarrays
ds1 = xr.open_dataset(gdf.get('netcdf_files/U500storm.cdf'))
ds2 = xr.open_dataset(gdf.get('netcdf_files/V500storm.cdf'))

################################################################################
# Plot:

# Set figure
fig = plt.figure(figsize=(10, 10))

# Create first subplot on figure for map
ax = fig.add_axes([.1, .2, .8, .6],
                  projection=ccrs.LambertAzimuthalEqualArea(
                      central_longitude=-100, central_latitude=40),
                  frameon=False,
                  aspect='auto')
Example #21
0
# Set to True to activate diagnostic print statements throughout the code
debug = False


# Convenience function to run diagnostic print statements when "debug" is set to True.
def print_debug(message):
    if debug:
        print(message)


###############################################################################
# Read in data:

# Open a netCDF data file using xarray default engine and load the data into xarrays
ds = xr.open_dataset(gdf.get('netcdf_files/slp.mon.mean.nc'))

# Print a content summary
print_debug('\n\nds.slp.attrs:\n')
print_debug(ds.slp.attrs)

###############################################################################
# Flip and sort longitude coordinates:

# To facilitate data subsetting

print_debug(
    f'\n\nBefore flip, longitude range is [{ds["lon"].min().data}, {ds["lon"].max().data}].'
)

ds["lon"] = ((ds["lon"] + 180) % 360) - 180
Example #22
0
import numpy as np
from sklearn.cluster import DBSCAN
import matplotlib.pyplot as plt
from matplotlib import colors
import matplotlib.ticker as mticker
import warnings

import geocat.datafiles as gdf
import geocat.viz.util as gvutil

###############################################################################
# Read in data:

# Open a netCDF data file using xarray default engine and
# load the data into xarrays
ds = xr.open_dataset(gdf.get("netcdf_files/slp.1963.nc"), decode_times=False)

# Get data from the 21st timestep
pressure = ds.slp[21, :, :]

# Translate float values to short values
pressure = pressure.astype('float32')

# Convert Pa to hPa data
pressure = pressure * 0.01

# Fix the artifact of not-shown-data around 0 and 360-degree longitudes
wrap_pressure = gvutil.xr_add_cyclic_longitudes(pressure, "lon")

###############################################################################
Example #23
0
"""

###############################################################################
# Import packages:
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr

import geocat.datafiles as gdf
from geocat.viz import util as gvutil

################################################################################
# Read in data:

# Open a netCDF data file using xarray default engine and load the data into xarrays
ds = xr.open_dataset(gdf.get("netcdf_files/TestData.xy3.nc"))
# Extract a slice of the data
ds = ds.isel(case=0, time=slice(0, 36))

################################################################################
# Plot:

# Generate figure (set its size (width, height) in inches) and axes (with two different y-axes)
fig, ax1 = plt.subplots(figsize=(7, 6.5))

# Plot data
ax1.plot(ds.time, ds.T, color="blue", linestyle="-", linewidth=0.9)

# Usa geocat.viz.util convenience function to add minor and major tick lines
gvutil.add_major_minor_ticks(ax1, x_minor_per_major=5, labelsize=14)
Example #24
0
###############################################################################
# Import packages:
import numpy as np
import xarray as xr
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import math

import geocat.datafiles as gdf
from geocat.viz import util as gvutil

###############################################################################
# Read in data:

# Open a netCDF data file using xarray default engine and load the data into xarrays
ds = xr.open_dataset(gdf.get('netcdf_files/AtmJan360_xy_4.nc'),
                     decode_times=False)

# Extract a slice of the data
ds = ds['T']
t = ds.isel(lev=0).drop('lev')
t = t.isel(lat=32).drop('lat')
t = t.isel(lon=29).drop('lon')

###############################################################################
# Plot with standard markers:
plt.figure(figsize=(8, 8))
ax = plt.axes()

plt.scatter(t.time, t.data, color='red')
Example #25
0
###############################################################################
# Import packages
import numpy as np
import matplotlib.pyplot as plt

import geocat.datafiles as gdf
from geocat.viz import util as gvutil

###############################################################################
# Read in data:

# Open a ascii data file using numpy's loadtxt
# Specify the delimiter from the file
# Read in the data as a floats
x, y = np.loadtxt(gdf.get("ascii_files/regress_1.txt"),
                  delimiter=',',
                  unpack=True,
                  dtype=float)

###############################################################################
# Calculate regression:

# Use numpy's polyfit to calculate a linear regression
# This function outputs [a, b], where y = ax + b in the regression fit
[a, b] = np.polyfit(x, y, 1)

###############################################################################
# Transform the found regression model for plotting

# Now that we have a y = ax + b, we can evaluate this model over a range,
Example #26
0
import matplotlib.pyplot as plt
import xarray as xr
import os

from wrf import (to_np, getvar, CoordPair, vertcross, latlon_coords)
import geocat.datafiles as gdf
import geocat.viz.util as gvutil

###############################################################################
# Read in the data

# Specify the necessary variables needed from the data set in order to use 'z' and 'QVAPOR'
toinclude = ['PH', 'P', 'HGT', 'PHB', 'QVAPOR']
# Read in necessary datasets
ds = xr.open_mfdataset([
    gdf.get('netcdf_files/wrfout_d03_2012-04-22_23_00_00_Z.nc'),
    gdf.get('netcdf_files/wrfout_d03_2012-04-22_23_00_00_QV.nc')
])

# specify a unique output file name to use to read in combined dataset later
file3 = 'wrfout_d03_2012-04-22_23.nc'
mrg = ds[toinclude].to_netcdf(file3)

# Read in the data and extract variables
wrfin = Dataset(('wrfout_d03_2012-04-22_23.nc'))

z = getvar(wrfin, "z")
qv = getvar(wrfin, "QVAPOR")
# Pull lat/lon coords from QVAPOR data using wrf-python tools
lats, lons = latlon_coords(qv)
from cartopy.feature import ShapelyFeature, OCEAN, LAKES, LAND
from cartopy.crs import PlateCarree
from cartopy.mpl.patch import geos_to_path
from cartopy.io.shapereader import Reader as ShapeReader, natural_earth

import geocat.datafiles as gdf
from geocat.viz import cmaps as gvcmaps
from geocat.viz import util as gvutil

###############################################################################
# Read in data:
# --------------------------

# Open a netCDF data file using xarray default engine and load the data into xarrays, as well as extract slices for
# ``time=0`` and the ``lev=500`` hPa level
ds = xr.open_dataset(gdf.get("netcdf_files/uvt.nc")).sel(time=0, lev=500)

# For convenience only, extract the U,V,T and lat and lon variables
U = ds["U"]
V = ds["V"]
T = ds["T"]

lat = ds["lat"]
lon = ds["lon"]

###############################################################################
# Construct shape boundaries
# --------------------------
#
# Using Cartopy's interface to the Natural Earth Collection of shapefiles
# and geographical shape data, we construct the geographical boundaries
Example #28
0
###############################################################################
# Import packages:
import numpy as np
import xarray as xr
import cartopy.crs as ccrs
import matplotlib.pyplot as plt

import geocat.datafiles as gdf
from geocat.viz import cmaps as gvcmaps
from geocat.viz import util as gvutil

###############################################################################
# Read in data:

# Open a netCDF data file using xarray default engine and load the data into xarrays
ds = xr.open_dataset(gdf.get("netcdf_files/cone.nc"))
u = ds.u.isel(time=4)

###############################################################################
# Plot:

# Generate figure (set its size (width, height) in inches)
plt.figure(figsize=(10, 6))

# Generate axes, using Cartopy
projection = ccrs.PlateCarree()
ax = plt.axes(projection=projection)

# Import an NCL colormap
newcmp = gvcmaps.gui_default
Example #29
0
import numpy as np
import xarray as xr
import cartopy.feature as cfeature
import cartopy.crs as ccrs
import matplotlib.pyplot as plt

import geocat.datafiles as gdf
from geocat.viz import cmaps as gvcmaps
from geocat.viz import util as gvutil

###############################################################################
# Read in data:

# Open a netCDF data file using xarray default engine and load the data into xarrays
ds = xr.open_dataset(gdf.get("netcdf_files/h_avg_Y0191_D000.00.nc"),
                     decode_times=False)

# Extract a slice of the data
t = ds.T.isel(time=0, z_t=0).sel(lat_t=slice(-60, 30), lon_t=slice(30, 120))

###############################################################################
# Plot:

fig = plt.figure(figsize=(12, 12))

def Plot(color, row, col, pos, title):

    # Generate axes, using Cartopy, drawing coastlines, and adding features
    projection = ccrs.PlateCarree()
    ax1 = plt.subplot(row, col, pos, projection=projection)
Example #30
0
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import pandas as pd
import metpy.calc as mpcalc
from metpy.plots import  SkewT
from metpy.units import units

import geocat.datafiles as gdf
from geocat.viz import util as gvutil

###############################################################################
# Read in data:

# Open a netCDF data file using xarray default engine and load the data into xarrays
ds = pd.read_csv(gdf.get('ascii_files/sounding_ATS.csv'),  header=None)

# Extract the data
p = ds[0].values*units.hPa   # Pressure [mb/hPa]
tc = ds[1].values*units.degC  # Temperature [C]
tdc = ds[2].values*units.degC  # Dew pt temp  [C]
wspd = ds[5].values*units.knots    # Wind speed   [knots or m/s]
wdir = ds[6].values*units.degrees    # Meteorological wind dir
u, v = mpcalc.wind_components(wspd, wdir)   # Calculate wind components 

###############################################################################
# Plot

fig = plt.figure(figsize=(12,12))
# Adding the "rotation" kwarg will over-ride the default MetPy rotation of 
# 30 degrees for the 45 degree default found in NCL Skew-T plots