Esempio n. 1
0
def basic_map(proj):
    """Make our basic default map for plotting"""
    fig = plt.figure(figsize=(15, 10))
    add_metpy_logo(fig, 0, 80, size='large')
    view = fig.add_axes([0, 0, 1, 1], projection=proj)
    view.set_extent([-120, -70, 20, 50])
    view.add_feature(cfeature.STATES.with_scale('50m'))
    view.add_feature(cfeature.OCEAN)
    view.add_feature(cfeature.COASTLINE)
    view.add_feature(cfeature.BORDERS, linestyle=':')
    return fig, view
Esempio n. 2
0
def make_skewt():
    # Get the data
    date = request.args.get('date')
    time = request.args.get('time')
    region = request.args.get('region')
    station = request.args.get('station')
    date = datetime.strptime(date, '%Y%m%d')
    date = datetime(date.year, date.month, date.day, int(time))
    df = get_sounding_data(date, region, station)
    p = df['pressure'].values * units(df.units['pressure'])
    T = df['temperature'].values * units(df.units['temperature'])
    Td = df['dewpoint'].values * units(df.units['dewpoint'])
    u = df['u_wind'].values * units(df.units['u_wind'])
    v = df['v_wind'].values * units(df.units['v_wind'])

    # Make the Skew-T
    fig = plt.figure(figsize=(9, 9))
    add_metpy_logo(fig, 115, 100)
    skew = SkewT(fig, rotation=45)

    # Plot the data using normal plotting functions, in this case using
    # log scaling in Y, as dictated by the typical meteorological plot
    skew.plot(p, T, 'tab:red')
    skew.plot(p, Td, 'tab:green')
    skew.plot_barbs(p, u, v)
    skew.ax.set_ylim(1000, 100)
    skew.ax.set_xlim(-40, 60)

    # Calculate LCL height and plot as black dot
    lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0])
    skew.plot(lcl_pressure, lcl_temperature, 'ko', markerfacecolor='black')

    # Calculate full parcel profile and add to plot as black line
    prof = mpcalc.parcel_profile(p, T[0], Td[0]).to('degC')
    skew.plot(p, prof, 'k', linewidth=2)

    # Shade areas of CAPE and CIN
    skew.shade_cin(p, T, prof)
    skew.shade_cape(p, T, prof)

    # An example of a slanted line at constant T -- in this case the 0
    # isotherm
    skew.ax.axvline(0, color='c', linestyle='--', linewidth=2)

    # Add the relevant special lines
    skew.plot_dry_adiabats()
    skew.plot_moist_adiabats()
    skew.plot_mixing_lines()

    canvas = FigureCanvas(fig)
    img = BytesIO()
    fig.savefig(img)
    img.seek(0)
    return send_file(img, mimetype='image/png')
def basic_map(proj):
    """Make our basic default map for plotting"""
    fig = plt.figure(figsize=(15, 10))
    add_metpy_logo(fig, 0, 80, size='large')
    view = fig.add_axes([0, 0, 1, 1], projection=proj)
    view.set_extent([-120, -70, 20, 50])
    view.add_feature(cfeature.STATES.with_scale('50m'))
    view.add_feature(cfeature.OCEAN)
    view.add_feature(cfeature.COASTLINE)
    view.add_feature(cfeature.BORDERS, linestyle=':')
    return fig, view
Esempio n. 4
0
def basic_map(proj):
    """Make our basic default map for plotting"""
    fig = plt.figure(figsize=(15, 10))
    add_metpy_logo(fig, 0, 80, size='large')
    view = fig.add_axes([0, 0, 1, 1], projection=proj)
    view._hold = True  # Work-around for CartoPy 0.16/Matplotlib 3.0.0 incompatibility
    view.set_extent([-120, -70, 20, 50])
    view.add_feature(cfeature.STATES.with_scale('50m'))
    view.add_feature(cfeature.OCEAN)
    view.add_feature(cfeature.COASTLINE)
    view.add_feature(cfeature.BORDERS, linestyle=':')
    return fig, view
Esempio n. 5
0
def basic_map(proj):
    """Make our basic default map for plotting"""
    fig = plt.figure(figsize=(15, 10))
    add_metpy_logo(fig, 0, 80, size='large')
    view = fig.add_axes([0, 0, 1, 1], projection=proj)
    view.set_extent([-120, -70, 20, 50])
    view.add_feature(
        cartopy.feature.NaturalEarthFeature(
            category='cultural',
            name='admin_1_states_provinces_lakes',
            scale='50m',
            facecolor='none'))
    view.add_feature(cartopy.feature.OCEAN)
    view.add_feature(cartopy.feature.COASTLINE)
    view.add_feature(cartopy.feature.BORDERS, linestyle=':')
    return view
Esempio n. 6
0
def plot_skewt(df):
    # We will pull the data out of the example dataset into individual variables
    # and assign units.
    p = df['pressure'].values * units.hPa
    T = df['temperature'].values * units.degC
    Td = df['dewpoint'].values * units.degC
    wind_speed = df['speed'].values * units.knots
    wind_dir = df['direction'].values * units.degrees
    u, v = mpcalc.wind_components(wind_speed, wind_dir)

    # Create a new figure. The dimensions here give a good aspect ratio.
    fig = plt.figure(figsize=(9, 9))
    add_metpy_logo(fig, 115, 100)
    skew = SkewT(fig, rotation=45)

    # Plot the data using normal plotting functions, in this case using
    # log scaling in Y, as dictated by the typical meteorological plot
    skew.plot(p, T, 'r')
    skew.plot(p, Td, 'g')
    skew.plot_barbs(p, u, v)
    skew.ax.set_ylim(1000, 100)
    skew.ax.set_xlim(-40, 60)

    # Calculate LCL height and plot as black dot
    lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0])
    skew.plot(lcl_pressure, lcl_temperature, 'ko', markerfacecolor='black')

    # Calculate full parcel profile and add to plot as black line
    prof = mpcalc.parcel_profile(p, T[0], Td[0]).to('degC')
    skew.plot(p, prof, 'k', linewidth=2)

    # An example of a slanted line at constant T -- in this case the 0
    # isotherm
    skew.ax.axvline(0, color='c', linestyle='--', linewidth=2)

    # Add the relevant special lines
    skew.plot_dry_adiabats()
    skew.plot_moist_adiabats()
    skew.plot_mixing_lines()

    return skew
Esempio n. 7
0
def test_add_logo_invalid_size():
    """Test adding a logo to a figure with an invalid size specification."""
    fig = plt.figure(figsize=(9, 9))
    with pytest.raises(ValueError):
        add_metpy_logo(fig, size='jumbo')
Esempio n. 8
0
"""
NEXRAD Level 3 File
===================

Use MetPy to read information from a NEXRAD Level 3 (NIDS product) file and plot
"""
import matplotlib.pyplot as plt
import numpy as np

from metpy.cbook import get_test_data
from metpy.io import Level3File
from metpy.plots import add_metpy_logo, add_timestamp, colortables

###########################################
fig, axes = plt.subplots(1, 2, figsize=(15, 8))
add_metpy_logo(fig, 190, 85, size='large')
for v, ctable, ax in zip(('N0Q', 'N0U'), ('NWSReflectivity', 'NWSVelocity'), axes):
    # Open the file
    name = get_test_data('nids/KOUN_SDUS54_{}TLX_201305202016'.format(v), as_file_obj=False)
    f = Level3File(name)

    # Pull the data out of the file object
    datadict = f.sym_block[0][0]

    # Turn into an array, then mask
    data = np.ma.array(datadict['data'])
    data[data == 0] = np.ma.masked

    # Grab azimuths and calculate a range based on number of gates
    az = np.array(datadict['start_az'] + [datadict['end_az'][-1]])
    rng = np.linspace(0, f.max_range, data.shape[-1] + 1)
Esempio n. 9
0
###########################################

# Create CartoPy projection information for the file
globe = ccrs.Globe(ellipse='sphere',
                   semimajor_axis=proj_var.earth_radius,
                   semiminor_axis=proj_var.earth_radius)
proj = ccrs.LambertConformal(
    central_longitude=proj_var.longitude_of_central_meridian,
    central_latitude=proj_var.latitude_of_projection_origin,
    standard_parallels=[proj_var.standard_parallel],
    globe=globe)

###########################################

# Plot the image
fig = plt.figure(figsize=(10, 12))
add_metpy_logo(fig, 125, 145)
ax = fig.add_subplot(1, 1, 1, projection=proj)
wv_norm, wv_cmap = ctables.registry.get_with_range('WVCIMSS', 100, 260)
wv_cmap.set_under('k')
im = ax.imshow(dat[:],
               cmap=wv_cmap,
               norm=wv_norm,
               extent=ds.img_extent,
               origin='upper')
ax.add_feature(cfeature.COASTLINE.with_scale('50m'))
add_timestamp(ax, f.prod_desc.datetime, y=0.02, high_contrast=True)

plt.show()
Esempio n. 10
0
def SkewT_plot(p,
               T,
               Td,
               heights,
               u=0,
               v=0,
               wind_barb=0,
               p_lims=[1000, 100],
               T_lims=[-50, 35],
               metpy_logo=0,
               plt_lfc=0,
               plt_lcl=0,
               plt_el=0,
               title=None):

    #plotting
    fig = plt.figure(figsize=(10, 10))
    skew = plots.SkewT(fig)

    skew.plot(p, T, 'red')  #Virtual Temperature
    skew.plot(p, Td, 'green')  #Dewpoint

    skew.ax.set_ylim(p_lims)
    skew.ax.set_xlim(T_lims)

    if wind_barb == 1:
        # resampling wind barbs
        interval = np.logspace(2, 3) * units.hPa
        idx = mpcalc.resample_nn_1d(p, interval)
        skew.plot_barbs(p[idx], u[idx], v[idx])

    #Showing Adiabasts and Mixing Ratio Lines
    skew.plot_dry_adiabats()
    skew.plot_moist_adiabats()
    skew.plot_mixing_lines()

    parcel_path = mpcalc.parcel_profile(p, T[0], Td[0])
    skew.plot(p, parcel_path, color='k')

    # CAPE and CIN
    skew.shade_cape(p, T, parcel_path)
    skew.shade_cin(p, T, parcel_path)

    # Isotherms and Isobars
    # skew.ax.axhline(500 * units.hPa, color='k')
    # skew.ax.axvline(0 * units.degC, color='c')

    # LCL, LFC, EL
    lcl_p, lcl_T = mpcalc.lcl(p[0], T[0], Td[0])
    lfc_p, lfc_T = mpcalc.lfc(p, T, Td)
    el_p, el_T = mpcalc.el(p, T, Td)

    if plt_lfc == 1:
        skew.ax.axhline(lfc_p, color='k')

    if plt_lcl == 1:
        skew.ax.axhline(lcl_p, color='k')
        # skew.ax.text(lcl_p, )

    if plt_el == 1:
        skew.ax.axhline(el_p, color='k')

    if metpy_logo == 1: plots.add_metpy_logo(fig, x=55, y=50)

    decimate = 3
    for p, T, heights in zip(df['pressure'][::decimate],
                             df['temperature'][::decimate],
                             df['height'][::decimate]):
        if p >= 700: skew.ax.text(T + 1, p, round(heights, 0))

    plt.title(title)

    plt.show()
    return
Esempio n. 11
0
###########################################
# We will pull the data out of the example dataset into individual variables and
# assign units.

p = df['pressure'].values * units.hPa
T = df['temperature'].values * units.degC
Td = df['dewpoint'].values * units.degC
wind_speed = df['speed'].values * units.knots
wind_dir = df['direction'].values * units.degrees
u, v = mpcalc.wind_components(wind_speed, wind_dir)

###########################################

# Create a new figure. The dimensions here give a good aspect ratio
fig = plt.figure(figsize=(9, 9))
add_metpy_logo(fig, 630, 80, size='large')

# Grid for plots
gs = gridspec.GridSpec(3, 3)
skew = SkewT(fig, rotation=45, subplot=gs[:, :2])

# Plot the data using normal plotting functions, in this case using
# log scaling in Y, as dictated by the typical meteorological plot
skew.plot(p, T, 'r')
skew.plot(p, Td, 'g')
skew.plot_barbs(p, u, v)
skew.ax.set_ylim(1000, 100)

# Add the relevant special lines
skew.plot_dry_adiabats()
skew.plot_moist_adiabats()
def Map_PVJet(i, im_save_path):
    from siphon.catalog import TDSCatalog
    top_cat = TDSCatalog('http://thredds.ucar.edu/thredds/catalog.xml')
    ref = top_cat.catalog_refs['Forecast Model Data']
    new_cat = ref.follow()
    model = new_cat.catalog_refs[4]
    gfs_cat = model.follow()
    ds = gfs_cat.datasets[1]
    gfs_cat.datasets[1]
    subset = ds.subset()
    query_data = subset.query()
    query_data.lonlat_box(west=-130, east=-50, south=10, north=60)

    # Allow for NetCDF files
    query_data.accept('netcdf4')
    query_data.time(i)
    query_data.variables('Geopotential_height_potential_vorticity_surface',
                         'Geopotential_height_isobaric',
                         'u-component_of_wind_isobaric',
                         'v-component_of_wind_isobaric',
                         'Relative_humidity_isobaric',
                         "Pressure_reduced_to_MSL_msl")
    #230., 295., 15., 45.
    #query.lonlat_box(west=230., east=295., south=15., north=45.)
    query_data.lonlat_box(west=-130, east=-50, south=10, north=60)
    query_data.accept('netcdf4')
    data = subset.get_data(query_data)
    PV_Heights = data.variables[
        'Geopotential_height_potential_vorticity_surface'][:].squeeze()

    PV_1 = np.where(data.variables['potential_vorticity_surface'][:] ==
                    1.9999999949504854E-6)[0][0]
    PV_1st = PV_Heights[PV_1]
    lev_250 = np.where(data.variables['isobaric4'][:] == 25000)[0][0]

    hght_250 = data.variables['Geopotential_height_isobaric'][0, lev_250, :, :]
    u_250 = data.variables['u-component_of_wind_isobaric'][0, lev_250, :, :]
    v_250 = data.variables['v-component_of_wind_isobaric'][0, lev_250, :, :]
    lat = data.variables['lat'][:]
    lon = data.variables['lon'][:]
    mslp = data.variables['Pressure_reduced_to_MSL_msl'][:].squeeze()
    # Create a figure object, title it, and do the plots.
    fig = plt.figure(figsize=(17., 11.))

    add_metpy_logo(fig, 30, 940, size='small')

    # Add the map and set the extent
    ax = plt.subplot(1, 1, 1, projection=plotcrs)

    # Add state boundaries to plot
    ax.add_feature(states_provinces, edgecolor='b', linewidth=1)

    # Add country borders to plot
    ax.add_feature(country_borders, edgecolor='k', linewidth=1)

    # Convert number of hours since the reference time into an actual date
    time_var = data.variables[find_time_var(
        data.variables['v-component_of_wind_isobaric'])]
    time_final = num2date(time_var[:].squeeze(), time_var.units)
    print(
        str(time_final)[:4] + "_" + str(time_final)[5:7] + "_" +
        str(time_final)[8:10] + "_" + str(time_final)[11:13] + "Z")
    file_time = str(time_final)[:4] + "_" + str(time_final)[5:7] + "_" + str(
        time_final)[8:10] + "_" + str(time_final)[11:13] + "Z"

    # Plot Title
    plt.title('GFS: PV and Jet Streaks (m/s)', loc='left', fontsize=16)
    plt.title(' {0:%d %B %Y %H:%MZ}'.format(time_final),
              loc='right',
              fontsize=16)

    # Heights
    #---------------------------------------------------------------------------------------------------

    MIN = hght_250.min()
    MAX = hght_250.max()

    #print hght_250.min(),hght_250.max()
    hght_250_smooth = ndimage.gaussian_filter(hght_250, sigma=3,
                                              order=0) * units.meter

    clev250 = np.arange(MIN, MAX, 80)
    #cs = ax.contour(lon_2d, lat_2d, hght_250_smooth, clev250, colors='black', linewidths=2.0,
    #                linestyles='solid', transform=datacrs)
    #plt.clabel(cs, fontsize=10, inline=1, inline_spacing=10, fmt='%i',
    #           rightside_up=True, use_clabeltext=True)

    # Winds
    #---------------------------------------------------------------------------------------------------
    #lon_slice = slice(None, None, 7)
    #lat_slice = slice(None, None, 7)
    #ax4.barbs(lon[lon_slice], lat[lat_slice],
    #         u_250[lon_slice, lat_slice].magnitude,
    #         v_250[lon_slice, lat_slice].magnitude,
    #         transform=ccrs.PlateCarree(), zorder=2)

    #clev_mslp = np.arange(0, 1200, 3)
    #cs = ax.contour(lon, lat, mslp/100, clev_mslp, colors='k',alpha=0.5,
    #linestyles='solid', transform=datacrs,zorder=5) # cmap='rainbow, linewidths=3

    #plt.clabel(cs, fontsize=10, inline=1, inline_spacing=10, fmt='%i',
    #       rightside_up=True, use_clabeltext=True,colors='k')

    wspd250 = mpcalc.get_wind_speed(u_250, v_250)
    #print wspd250.min()
    clevsped250 = np.arange(50, 100, 5)
    cf = ax.contour(lon,
                    lat,
                    wspd250,
                    clevsped250,
                    colors='r',
                    transform=datacrs)
    plt.clabel(cf,
               fontsize=10,
               inline=1,
               inline_spacing=10,
               fmt='%i',
               rightside_up=True,
               use_clabeltext=True,
               colors='k')
    #cf = ax.contourf(lon_2d, lat_2d, wspd250, clevsped250, cmap="gist_ncar", transform=datacrs)

    #cbar = plt.colorbar(cf, cax=cax, orientation='horizontal', extend='max', extendrect=True,pad=0.2)
    #cbaxes = fig.add_axes(colorbar_axis)

    #cbar = plt.colorbar(cf, orientation='horizontal',cax=cbaxes)

    cs2 = ax.contourf(lon,
                      lat,
                      PV_1st,
                      100,
                      alpha=0.7,
                      antialiased=True,
                      transform=datacrs,
                      cmap='cubehelix_r')

    cbaxes = fig.add_axes(colorbar_axis)  # [left, bottom, width, height]

    cbar = plt.colorbar(cs2, orientation='horizontal', cax=cbaxes)

    ax.set_extent(extent, datacrs)

    plt.close(fig)
    #---------------------------------------------------------------------------------------------------
    #---------------------------------------------------------------------------------------------------
    PV_Jet = im_save_path + "GFS/PV_Jet/"
    if not os.path.isdir(PV_Jet):
        os.makedirs(PV_Jet)
    fig.savefig(PV_Jet + "Jet_PV_" + file_time + ".png",
                bbox_inches='tight',
                dpi=120)

    print('done.')
Esempio n. 13
0
isentrh = 100 * mpcalc.relative_humidity_from_specific_humidity(isentspech, isenttmp, isentprs)

#######################################
# **Plotting the Isentropic Analysis**

# Set up our projection
crs = ccrs.LambertConformal(central_longitude=-100.0, central_latitude=45.0)

# Coordinates to limit map area
bounds = [(-122., -75., 25., 50.)]
# Choose a level to plot, in this case 296 K
level = 0

fig = plt.figure(figsize=(17., 12.))
add_metpy_logo(fig, 120, 245, size='large')
ax = fig.add_subplot(1, 1, 1, projection=crs)
ax.set_extent(*bounds, crs=ccrs.PlateCarree())
ax.add_feature(cfeature.COASTLINE.with_scale('50m'), linewidth=0.75)
ax.add_feature(cfeature.STATES, linewidth=0.5)

# Plot the surface
clevisent = np.arange(0, 1000, 25)
cs = ax.contour(lon, lat, isentprs[level, :, :], clevisent,
                colors='k', linewidths=1.0, linestyles='solid', transform=ccrs.PlateCarree())
ax.clabel(cs, fontsize=10, inline=1, inline_spacing=7,
          fmt='%i', rightside_up=True, use_clabeltext=True)

# Plot RH
cf = ax.contourf(lon, lat, isentrh[level, :, :], range(10, 106, 5),
                 cmap=plt.cm.gist_earth_r, transform=ccrs.PlateCarree())
Esempio n. 14
0
# then refine the number of stations plotted by setting a 300km radius
point_locs = proj.transform_points(ccrs.PlateCarree(), data['longitude'].values,
                                   data['latitude'].values)
data = data[reduce_point_density(point_locs, 300000.)]

###########################################
# The payoff
# ----------

# Change the DPI of the resulting figure. Higher DPI drastically improves the
# look of the text rendering.
plt.rcParams['savefig.dpi'] = 255

# Create the figure and an axes set to the projection.
fig = plt.figure(figsize=(20, 10))
add_metpy_logo(fig, 1100, 300, size='large')
ax = fig.add_subplot(1, 1, 1, projection=proj)

# Add some various map elements to the plot to make it recognizable.
ax.add_feature(cfeature.LAND)
ax.add_feature(cfeature.OCEAN)
ax.add_feature(cfeature.LAKES)
ax.add_feature(cfeature.COASTLINE)
ax.add_feature(cfeature.STATES)
ax.add_feature(cfeature.BORDERS)

# Set plot bounds
ax.set_extent((-118, -73, 23, 50))

#
# Here's the actual station plot
Esempio n. 15
0
def test_add_logo_invalid_size():
    """Test adding a logo to a figure with an invalid size specification."""
    fig = plt.figure(figsize=(9, 9))
    with pytest.raises(ValueError):
        add_metpy_logo(fig, size='jumbo')
Esempio n. 16
0
def test_add_metpy_logo_large():
    """Test adding a large MetPy logo to a figure."""
    fig = plt.figure(figsize=(9, 9))
    add_metpy_logo(fig, size='large')
    return fig
Esempio n. 17
0
def test_add_metpy_logo_small():
    """Test adding a MetPy logo to a figure."""
    fig = plt.figure(figsize=(9, 9))
    add_metpy_logo(fig)
    return fig
Esempio n. 18
0
def Map_Jets(i, im_save_path):
    from siphon.catalog import TDSCatalog
    top_cat = TDSCatalog('http://thredds.ucar.edu/thredds/catalog.xml')
    ref = top_cat.catalog_refs['Forecast Model Data']
    new_cat = ref.follow()
    model = new_cat.catalog_refs[4]
    gfs_cat = model.follow()
    ds = gfs_cat.datasets[1]
    subset = ds.subset()
    query_data = subset.query()
    query_data.lonlat_box(west=-130, east=-50, south=10, north=60)

    # Allow for NetCDF files
    query_data.accept('netcdf4')
    query_data.time(i)
    data = query_data.variables('Geopotential_height_isobaric',
                                'Pressure_reduced_to_MSL_msl',
                                'u-component_of_wind_isobaric',
                                'v-component_of_wind_isobaric')

    # Finally attempt to access the data
    data = subset.get_data(query_data)
    lat = data.variables['lat'][:].squeeze()
    lon = data.variables['lon'][:].squeeze()
    lev_250 = np.where(data.variables['isobaric4'][:] == 25000)[0][0]

    hght_250 = data.variables['Geopotential_height_isobaric'][0, lev_250, :, :]
    u_250 = data.variables['u-component_of_wind_isobaric'][0, lev_250, :, :]
    v_250 = data.variables['v-component_of_wind_isobaric'][0, lev_250, :, :]

    # Create a figure object, title it, and do the plots.
    fig = plt.figure(figsize=(17., 11.))

    add_metpy_logo(fig, 30, 940, size='small')

    # Add the map and set the extent
    ax6 = plt.subplot(1, 1, 1, projection=plotcrs)

    # Add state boundaries to plot
    ax6.add_feature(states_provinces, edgecolor='b', linewidth=1)

    # Add country borders to plot
    ax6.add_feature(country_borders, edgecolor='k', linewidth=1)

    # Convert number of hours since the reference time into an actual date
    time_var = data.variables[find_time_var(
        data.variables['v-component_of_wind_isobaric'])]
    time_final = num2date(time_var[:].squeeze(), time_var.units)
    print(
        str(time_final)[:4] + "_" + str(time_final)[5:7] + "_" +
        str(time_final)[8:10] + "_" + str(time_final)[11:13] + "Z")
    file_time = str(time_final)[:4] + "_" + str(time_final)[5:7] + "_" + str(
        time_final)[8:10] + "_" + str(time_final)[11:13] + "Z"

    # Plot Title
    plt.title('GFS: 250mb Heights and Jet Streaks (m/s)',
              loc='left',
              fontsize=16)
    plt.title(' {0:%d %B %Y %H:%MZ}'.format(time_final),
              loc='right',
              fontsize=16)

    # Heights
    #---------------------------------------------------------------------------------------------------

    MIN = hght_250.min()
    MAX = hght_250.max()

    #print hght_250.min(),hght_250.max()
    hght_250 = ndimage.gaussian_filter(hght_250, sigma=3,
                                       order=0) * units.meter

    clev250 = np.arange(MIN, MAX, 80)
    cs = ax6.contour(lon,
                     lat,
                     hght_250.m,
                     clev250,
                     colors='black',
                     linewidths=2.0,
                     linestyles='solid',
                     transform=ccrs.PlateCarree())
    #plt.clabel(cs, fontsize=10, inline=1, inline_spacing=10, fmt='%i',
    #           rightside_up=True, use_clabeltext=True)

    # Winds
    #---------------------------------------------------------------------------------------------------
    #lon_slice = slice(None, None, 7)
    #lat_slice = slice(None, None, 7)
    #ax4.barbs(lon[lon_slice], lat[lat_slice],
    #         u_250[lon_slice, lat_slice].magnitude,
    #         v_250[lon_slice, lat_slice].magnitude,
    #         transform=ccrs.PlateCarree(), zorder=2)

    wspd250 = mpcalc.get_wind_speed(u_250, v_250)
    clevsped250 = np.arange(50, 100, 1)
    cf = ax6.contourf(lon,
                      lat,
                      wspd250,
                      clevsped250,
                      cmap="gist_ncar",
                      transform=ccrs.PlateCarree())
    #cbar = plt.colorbar(cf, cax=cax, orientation='horizontal', extend='max', extendrect=True,pad=0.2)
    cbaxes = fig.add_axes(colorbar_axis)

    cbar = plt.colorbar(cf, orientation='horizontal', cax=cbaxes)

    ax6.set_extent(extent, datacrs)

    plt.close(fig)
    #---------------------------------------------------------------------------------------------------
    #---------------------------------------------------------------------------------------------------
    GFS_Jet = im_save_path + "GFS/Jets/"
    if not os.path.isdir(GFS_Jet):
        os.makedirs(GFS_Jet)
    fig.savefig(GFS_Jet + "250mb_Heights_Winds_" + file_time + ".png",
                bbox_inches='tight',
                dpi=120)

    print('done.')
    # Make an LCC map projection
    proj = ccrs.LambertConformal()

    # Plot the map
    fig = plt.figure(figsize=(12, 7))
    ax = plt.axes(projection=proj)
    ax.add_feature(cfeature.COASTLINE.with_scale('50m'))
    ax.add_feature(cfeature.OCEAN.with_scale('50m'))
    ax.add_feature(cfeature.LAND.with_scale('50m'))
    ax.add_feature(cfeature.BORDERS.with_scale('50m'), linestyle=':')
    ax.add_feature(cfeature.STATES.with_scale('50m'), linestyle=':')
    ax.add_feature(cfeature.LAKES.with_scale('50m'), alpha=0.5)
    ax.add_feature(cfeature.RIVERS.with_scale('50m'), alpha=0.5)

    add_timestamp(ax)
    add_metpy_logo(fig, x=300, y=350)

    scatter = ax.scatter(df.longitude, df.latitude,
                         c=df[args.var], transform=ccrs.PlateCarree(),
                         cmap=plt.get_cmap(args.cmap), vmin=args.min, vmax=args.max,
                         s=args.msize) # cm.Oranges or Use plt.get_cmap(str)

    plt.colorbar(scatter, orientation='horizontal',
                 label=args.var.replace('_', ' ').title(),
                 shrink=0.6, pad=0.05)

    #u, v = mpcalc.wind_components(df.wind_direction.values * units('m/s'), df.wind_direction.values * units.degrees)
    #x = df.longitude.values
    #y = df.latitude.values
    #ax.quiver(x, y, u.m, v.m, transform=ccrs.PlateCarree(), units='dots')
Esempio n. 20
0
def produce(data, conn, client):
    Year = data['inputData']['Year']
    Month = data['inputData']['Month']
    Day = data['inputData']['Day']
    Radar = data['inputData']['Radar']
    uid = data['uid']
    inputData = data['inputData']
    userID = data["userID"]

    numberOfPlots = 1
    scans = conn.get_avail_scans(Year, Month, Day,
                                 Radar)  # year, month and day
    results = conn.download(scans[numberOfPlots - 1], 'templocation')

    # fig = plt.figure(figsize=(16,12))
    for i, scan in enumerate(results.iter_success(), start=1):
        #         ax = fig.add_subplot(1,1,i)
        #         radar = scan.open_pyart()

        #         display = pyart.graph.RadarDisplay(radar)
        #         display.plot('reflectivity',0,ax=ax,title="{} {}".format(scan.radar_id,scan.scan_time))
        #         display.set_limits((-150, 150), (-150, 150), ax=ax)

        sweep = 0
        name = scan.open()
        f = Level2File(name)
        # First item in ray is header, which has azimuth angle
        az = np.array([ray[0].az_angle for ray in f.sweeps[sweep]])

        # 5th item is a dict mapping a var name (byte string) to a tuple
        # of (header, data array)
        ref_hdr = f.sweeps[sweep][0][4][b'REF'][0]
        ref_range = np.arange(
            ref_hdr.num_gates) * ref_hdr.gate_width + ref_hdr.first_gate
        ref = np.array([ray[4][b'REF'][1] for ray in f.sweeps[sweep]])

        rho_hdr = f.sweeps[sweep][0][4][b'RHO'][0]
        rho_range = (np.arange(rho_hdr.num_gates + 1) -
                     0.5) * rho_hdr.gate_width + rho_hdr.first_gate
        rho = np.array([ray[4][b'RHO'][1] for ray in f.sweeps[sweep]])

        fig, axes = plt.subplots(1, 2, figsize=(15, 8))
        add_metpy_logo(fig, 190, 85, size='large')
        for var_data, var_range, ax in zip((ref, rho), (ref_range, rho_range),
                                           axes):
            # Turn into an array, then mask
            data = np.ma.array(var_data)
            data[np.isnan(data)] = np.ma.masked

            # Convert az,range to x,y
            xlocs = var_range * np.sin(np.deg2rad(az[:, np.newaxis]))
            ylocs = var_range * np.cos(np.deg2rad(az[:, np.newaxis]))

            # Plot the data
            ax.pcolormesh(xlocs, ylocs, data, cmap='viridis')
            ax.set_aspect('equal', 'datalim')
            ax.set_xlim(-40, 20)
            ax.set_ylim(-30, 30)
            add_timestamp(ax, f.dt, y=0.02, high_contrast=True)

        pltName = 'images/' + str(uid + str(i) + '.png')
        plt.savefig(pltName)
        plt.close(fig)
        uploadImage = im.upload_image(pltName, title="Uploaded with PyImgur")
        link = str(uploadImage.link)

        body = {
            "inputData": inputData,
            "outputData": link,
            "uid": uid,
            "userID": userID
        }

        with (client.topics['dataAnalysisConsumerF']
              ).get_sync_producer() as producer:
            producer.produce(bytes(json.dumps(body), 'utf-8'))
# variable for plotting.

height, temp = log_interpolate_1d(plevs, pres, hgt, temperature, axis=1)

####################################
# **Plotting the Data for 700 hPa.**

# Set up our projection
crs = ccrs.LambertConformal(central_longitude=-100.0, central_latitude=45.0)

# Set the forecast hour
FH = 1

# Create the figure and grid for subplots
fig = plt.figure(figsize=(17, 12))
add_metpy_logo(fig, 470, 320, size='large')

# Plot 700 hPa
ax = plt.subplot(111, projection=crs)
ax.add_feature(cfeature.COASTLINE.with_scale('50m'), linewidth=0.75)
ax.add_feature(cfeature.STATES, linewidth=0.5)

# Plot the heights
cs = ax.contour(lon, lat, height[FH, 0, :, :], transform=ccrs.PlateCarree(),
                colors='k', linewidths=1.0, linestyles='solid')
ax.clabel(cs, fontsize=10, inline=1, inline_spacing=7,
          fmt='%i', rightside_up=True, use_clabeltext=True)

# Contour the temperature
cf = ax.contourf(lon, lat, temp[FH, 0, :, :], range(-20, 20, 1), cmap=plt.cm.RdBu_r,
                 transform=ccrs.PlateCarree())
Esempio n. 22
0
from metpy.io import Level3File
from metpy.plots import add_metpy_logo, add_timestamp, ctables

# Copyright (c) 2015 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""
NEXRAD Level 3 File
===================

Use MetPy to read information from a NEXRAD Level 3 (NIDS product) file and plot
"""

###########################################
fig, axes = plt.subplots(1, 2, figsize=(15, 8))
add_metpy_logo(fig, 190, 85, size="large")
for v, ctable, ax in zip(("N0Q", "N0U"), ("NWSReflectivity", "NWSVelocity"),
                         axes):
    # Open the file
    name = get_test_data("nids/KOUN_SDUS54_{}TLX_201305202016".format(v),
                         as_file_obj=False)
    f = Level3File(name)

    # Pull the data out of the file object
    datadict = f.sym_block[0][0]

    # Turn into an array, then mask
    data = np.ma.array(datadict["data"])
    data[data == 0] = np.ma.masked

    # Grab azimuths and calculate a range based on number of gates
Esempio n. 23
0
def Map_500_Vort(i,im_save_path):
    from siphon.catalog import TDSCatalog
    top_cat = TDSCatalog('http://thredds.ucar.edu/thredds/catalog.xml')
    ref = top_cat.catalog_refs['Forecast Model Data']
    new_cat = ref.follow()
    model = new_cat.catalog_refs[4]
    gfs_cat = model.follow()

    ds = gfs_cat.datasets[1]
    subset = ds.subset()
    query_data = subset.query()
    query_data.lonlat_box(west=-130, east=-50, south=10, north=60)

    # Allow for NetCDF files
    query_data.accept('netcdf4')
    query_data.time(i)
    data = query_data.variables("Absolute_vorticity_isobaric",'Geopotential_height_isobaric')

    # Finally attempt to access the data
    data = subset.get_data(query_data)
        #for i in data.variables.keys(): print "Variables:",i,"\n"

    # Pull out variables you want to use
    Vort = data.variables['Absolute_vorticity_isobaric']
    lev_500mb = np.where(data.variables['isobaric4'][:] == 50000)[0][0]
    Vort_500 = data.variables['Absolute_vorticity_isobaric'][0, lev_500mb, :, :]

    lat = data.variables['lat'][:].squeeze()
    lon = data.variables['lon'][:].squeeze()
    time_var = data.variables[find_time_var(data.variables['Absolute_vorticity_isobaric'])]

    # Convert number of hours since the reference time into an actual date
    time_final = num2date(time_var[:].squeeze(), time_var.units)
    print(str(time_final)[:4]+"_"+str(time_final)[5:7]+"_"+str(time_final)[8:10]+"_"+str(time_final)[11:13]+"Z")
    file_time = str(time_final)[:4]+"_"+str(time_final)[5:7]+"_"+str(time_final)[8:10]+"_"+str(time_final)[11:13]+"Z"

    # Combine 1D latitude and longitudes into a 2D grid of locations
    #lon_2d, lat_2d = np.meshgrid(lon, lat)

    # Create new figure
    fig = plt.figure(figsize=(17., 11.))

    add_metpy_logo(fig, 30, 940, size='small')

    # Add the map and set the extent
    ax = plt.subplot(111, projection=plotcrs)

    #Set the lat and lon boundaries
    ax.set_extent(extent, datacrs)

    # Add state boundaries to plot
    ax.add_feature(states_provinces, edgecolor='blue', linewidth=1)

    # Add country borders to plot
    ax.add_feature(country_borders, edgecolor='black', linewidth=1)

    # Plot Title
    plt.title('GFS: 500mb Vorticity and Heights', fontdict=font,loc='left')
    plt.title(' {0:%d %B %Y %H:%MZ}'.format(time_final), fontdict=font,loc='right')

    Min = Vort_500.min()
    Max = Vort_500.max()
    #print(Min,Max)

    #print hght_500.min(),hght_500.max()
    #hght_500 = ndimage.gaussian_filter(hght_500, sigma=3, order=0) * units.meter

    lev_500 = np.where(data.variables['isobaric4'][:] == 50000)[0][0]
    hght_500 = data.variables['Geopotential_height_isobaric'][0, lev_500, :, :]
    MIN = hght_500.min()
    MAX = hght_500.max()

    clev500 = np.arange(MIN, MAX, 70)
    cs = ax.contour(lon, lat, hght_500,clev500 ,colors='black', linewidths=2.0,
                    linestyles='solid', transform=ccrs.PlateCarree())
    vort_levels = np.arange(-.00055,.0007,0.00001)
    cs2 = ax.contourf(lon, lat, Vort_500,vort_levels,
                     transform=datacrs,cmap=my_cmap)

    cbaxes = fig.add_axes(colorbar_axis) # [left, bottom, width, height]

    #def myfmt(x, pos):
    #    return '{0:.1e}'.format(x)

    # apply formatter for colorbar labels
    #cbar = plt.colorbar(cs2, orientation='horizontal',cax=cbaxes,format=mpl.ticker.FuncFormatter(myfmt))
    cbar = plt.colorbar(cs2, orientation='horizontal',cax=cbaxes)

    #cbar = plt.colorbar(cs2, orientation='horizontal',cax=cbaxes,ticks = np.arange(-0.0006, 0.0006, 17),format=sfmt)
    cbar.set_label(r'$s{^-1}$')

    #plt.show()
    plt.close(fig)

    VORT = im_save_path+"GFS/Vorticity/"
    if not os.path.isdir(VORT):
        os.makedirs(VORT)
    outfile=VORT+"Vort_Heights_500mb_"+file_time+".png"
    fig.savefig(outfile,bbox_inches='tight',dpi=120)

    print("done.")
Esempio n. 24
0
surface_temp.metpy.convert_units('degF')
precip_water.metpy.convert_units('inches')
winds_300.metpy.convert_units('knots')

###########################################

# Smooth the height data
heights_300 = ndimage.gaussian_filter(ds['heights_300'][0], sigma=1.5, order=0)
heights_500 = ndimage.gaussian_filter(ds['heights_500'][0], sigma=1.5, order=0)

###########################################

# Create the figure and plot background on different axes
fig, axarr = plt.subplots(nrows=2, ncols=2, figsize=(20, 13), constrained_layout=True,
                          subplot_kw={'projection': crs})
add_metpy_logo(fig, 140, 120, size='large')
axlist = axarr.flatten()
for ax in axlist:
    plot_background(ax)

# Upper left plot - 300-hPa winds and geopotential heights
cf1 = axlist[0].contourf(lon_2d, lat_2d, winds_300, cmap='cool', transform=ccrs.PlateCarree())
c1 = axlist[0].contour(lon_2d, lat_2d, heights_300, colors='black', linewidths=2,
                       transform=ccrs.PlateCarree())
axlist[0].clabel(c1, fontsize=10, inline=1, inline_spacing=1, fmt='%i', rightside_up=True)
axlist[0].set_title('300-hPa Wind Speeds and Heights', fontsize=16)
cb1 = fig.colorbar(cf1, ax=axlist[0], orientation='horizontal', shrink=0.74, pad=0)
cb1.set_label('knots', size='x-large')

# Upper right plot - 500mb absolute vorticity and geopotential heights
cf2 = axlist[1].contourf(lon_2d, lat_2d, vort_500, cmap='BrBG', transform=ccrs.PlateCarree(),
Esempio n. 25
0
# Set up the map projection and set up a cartopy feature for state borders
proj = ccrs.LambertConformal(central_longitude=-95,
                             central_latitude=35,
                             standard_parallels=[35])

###########################################
# The payoff
# ----------

# Change the DPI of the resulting figure. Higher DPI drastically improves the
# look of the text rendering
plt.rcParams['savefig.dpi'] = 255

# Create the figure and an axes set to the projection
fig = plt.figure(figsize=(20, 10))
add_metpy_logo(fig, 1080, 290, size='large')
ax = fig.add_subplot(1, 1, 1, projection=proj)

# Add some various map elements to the plot to make it recognizable
ax.add_feature(cfeature.LAND)
ax.add_feature(cfeature.OCEAN)
ax.add_feature(cfeature.LAKES)
ax.add_feature(cfeature.COASTLINE)
ax.add_feature(cfeature.STATES)
ax.add_feature(cfeature.BORDERS, linewidth=2)

# Set plot bounds
ax.set_extent((-118, -73, 23, 50))

#
# Here's the actual station plot
Esempio n. 26
0
wind_direction = data['WDIR']
latitude = data['LAT']
longitude = data['LON']
station_id = data['STID']

# Take cardinal direction and convert to degrees, then convert to components
wind_direction = mpcalc.parse_angle(list(wind_direction))
u, v = mpcalc.wind_components(wind_speed.to('knots'), wind_direction)

###########################################
# Create the figure
# -----------------

# Create the figure and an axes set to the projection.
fig = plt.figure(figsize=(20, 8))
add_metpy_logo(fig, 70, 30, size='large')
ax = fig.add_subplot(1, 1, 1, projection=proj)

# Add some various map elements to the plot to make it recognizable.
ax.add_feature(cfeature.LAND)
ax.add_feature(cfeature.STATES.with_scale('50m'))

# Set plot bounds
ax.set_extent((-104, -93, 33.4, 37.2))

stationplot = StationPlot(ax,
                          longitude.values,
                          latitude.values,
                          clip_on=True,
                          transform=ccrs.PlateCarree(),
                          fontsize=12)
                                 t,
                                 interp_type='cressman',
                                 minimum_neighbors=3,
                                 search_radius=400000,
                                 hres=35000)

temp = np.ma.masked_where(np.isnan(temp), temp)

###########################################
# Set up the map and plot the interpolated grids appropriately.
levels = list(range(-20, 20, 1))
cmap = plt.get_cmap('viridis')
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)

fig = plt.figure(figsize=(20, 10))
add_metpy_logo(fig, 360, 120, size='large')
view = fig.add_subplot(1, 1, 1, projection=to_proj)

view.set_extent([-120, -70, 20, 50])
view.add_feature(cfeature.STATES.with_scale('50m'))
view.add_feature(cfeature.OCEAN)
view.add_feature(cfeature.COASTLINE.with_scale('50m'))
view.add_feature(cfeature.BORDERS, linestyle=':')

cs = view.contour(slpgridx,
                  slpgridy,
                  slp,
                  colors='k',
                  levels=list(range(990, 1034, 4)))
plt.clabel(cs, inline=1, fontsize=12, fmt='%i')
Esempio n. 28
0
# Temporary variables for ease
temp = testdata['T']
pres = testdata['P']
rh = testdata['RH']
ws = testdata['WS']
wsmax = testdata['WSMAX']
wd = testdata['WD']
date = testdata['DATE']

# ID For Plotting on Meteogram
probe_id = '0102A'

data = {'wind_speed': (np.array(ws) * units('m/s')).to(units('knots')),
        'wind_speed_max': (np.array(wsmax) * units('m/s')).to(units('knots')),
        'wind_direction': np.array(wd) * units('degrees'),
        'dewpoint': dewpoint_rh((np.array(temp) * units('degC')).to(units('K')),
                                np.array(rh) / 100.).to(units('degF')),
        'air_temperature': (np.array(temp) * units('degC')).to(units('degF')),
        'mean_slp': calc_mslp(np.array(temp), np.array(pres), hgt_example) * units('hPa'),
        'relative_humidity': np.array(rh), 'times': np.array(date)}

fig = plt.figure(figsize=(20, 16))
add_metpy_logo(fig, 250, 180)
meteogram = Meteogram(fig, data['times'], probe_id)
meteogram.plot_winds(data['wind_speed'], data['wind_direction'], data['wind_speed_max'])
meteogram.plot_thermo(data['air_temperature'], data['dewpoint'])
meteogram.plot_rh(data['relative_humidity'])
meteogram.plot_pressure(data['mean_slp'])
fig.subplots_adjust(hspace=0.5)
plt.show()
Esempio n. 29
0
###########################################
# We will pull the data out of the example dataset into individual variables and
# assign units.

p = df['pressure'].values * units.hPa
T = df['temperature'].values * units.degC
Td = df['dewpoint'].values * units.degC
wind_speed = df['speed'].values * units.knots
wind_dir = df['direction'].values * units.degrees
u, v = mpcalc.get_wind_components(wind_speed, wind_dir)

###########################################

# Create a new figure. The dimensions here give a good aspect ratio
fig = plt.figure(figsize=(9, 9))
add_metpy_logo(fig, 115, 100)

# Grid for plots
skew = SkewT(fig, rotation=45)

# Plot the data using normal plotting functions, in this case using
# log scaling in Y, as dictated by the typical meteorological plot
skew.plot(p, T, 'r')
skew.plot(p, Td, 'g')
skew.plot_barbs(p, u, v)
skew.ax.set_ylim(1000, 100)

# Add the relevant special lines
skew.plot_dry_adiabats()
skew.plot_moist_adiabats()
skew.plot_mixing_lines()
Esempio n. 30
0
tlons = tlatlons[:, :, 0]
tlats = tlatlons[:, :, 1]

# Coordinates to limit map area
bounds = [(-122., -75., 25., 50.)]
# Choose a level to plot, in this case 296 K
level = 0

# Get data to plot state and province boundaries
states_provinces = cfeature.NaturalEarthFeature(category='cultural',
                                                name='admin_1_states_provinces_lakes',
                                                scale='50m',
                                                facecolor='none')

fig = plt.figure(1, figsize=(17., 12.))
add_metpy_logo(fig, 120, 245, size='large')
ax = fig.add_subplot(1, 1, 1, projection=crs)
ax.set_extent(*bounds, crs=ccrs.PlateCarree())
ax.coastlines('50m', edgecolor='black', linewidth=0.75)
ax.add_feature(states_provinces, edgecolor='black', linewidth=0.5)

# Plot the surface
clevisent = np.arange(0, 1000, 25)
cs = ax.contour(tlons, tlats, isentprs[level, :, :], clevisent,
                colors='k', linewidths=1.0, linestyles='solid')
plt.clabel(cs, fontsize=10, inline=1, inline_spacing=7,
           fmt='%i', rightside_up=True, use_clabeltext=True)

# Plot RH
cf = ax.contourf(tlons, tlats, isentrh[level, :, :], range(10, 106, 5),
                 cmap=plt.cm.gist_earth_r)
Esempio n. 31
0
def test_add_metpy_logo_small():
    """Test adding a MetPy logo to a figure."""
    fig = plt.figure(figsize=(9, 9))
    add_metpy_logo(fig)
    return fig
Esempio n. 32
0
# variable for plotting.

height, temp = log_interpolate_1d(plevs, pres, hgt, temperature, axis=1)

####################################
# **Plotting the Data for 700 hPa.**

# Set up our projection
crs = ccrs.LambertConformal(central_longitude=-100.0, central_latitude=45.0)

# Set the forecast hour
FH = 1

# Create the figure and grid for subplots
fig = plt.figure(figsize=(17, 12))
add_metpy_logo(fig, 470, 320, size='large')

# Plot 700 hPa
ax = plt.subplot(111, projection=crs)
ax.add_feature(cfeature.COASTLINE.with_scale('50m'), linewidth=0.75)
ax.add_feature(cfeature.STATES, linewidth=0.5)

# Plot the heights
cs = ax.contour(lon,
                lat,
                height[FH, 0, :, :],
                transform=ccrs.PlateCarree(),
                colors='k',
                linewidths=1.0,
                linestyles='solid')
cs.clabel(fontsize=10,
###########################################

# Build dictionary of desired sweeps
sweeps_dict = sweep_info(radar_file,elevation_angle_limit=2)

# Create data array mappe to longitude/latitude
lons, lats, data = build_radar_data_array()

# Define extent of desired plot and get associated ticks
extent, x_ticks, y_ticks = plot_extent(lons,lats,rda_lon,rda_lat,0.45)

# Create plot
fig, axes = plt.subplots(1, 2, figsize=(11, 6),sharey=True,
                         subplot_kw={'projection': ccrs.PlateCarree()})
add_metpy_logo(fig, 575, 55, size='small')

plt.labelsize : 8
plt.tick_params(labelsize=8)

for y,a in zip([0,1],axes.ravel()):
    this_sweep = sweeps_dict[y]
    a.set_extent(extent, crs=ccrs.PlateCarree())
    a.tick_params(axis='both', labelsize=8)
    a.pcolormesh(this_sweep['lons'], this_sweep['lats'],
                 this_sweep['data'], cmap=this_sweep['cmap'],
                 vmin=this_sweep['vmin'],
                 vmax=this_sweep['vmax'],
                 transform=ccrs.PlateCarree())
    a.add_feature(cfeature.STATES, linewidth=0.5)
Esempio n. 34
0
# ID For Plotting on Meteogram
probe_id = '0102A'

data = {
    'wind_speed': (np.array(ws) * units('m/s')).to(units('knots')),
    'wind_speed_max': (np.array(wsmax) * units('m/s')).to(units('knots')),
    'wind_direction':
    np.array(wd) * units('degrees'),
    'dewpoint':
    dewpoint_from_relative_humidity((np.array(temp) * units.degC).to(units.K),
                                    np.array(rh) / 100.).to(units('degF')),
    'air_temperature': (np.array(temp) * units('degC')).to(units('degF')),
    'mean_slp':
    calc_mslp(np.array(temp), np.array(pres), hgt_example) * units('hPa'),
    'relative_humidity':
    np.array(rh),
    'times':
    np.array(date)
}

fig = plt.figure(figsize=(20, 16))
add_metpy_logo(fig, 250, 180)
meteogram = Meteogram(fig, data['times'], probe_id)
meteogram.plot_winds(data['wind_speed'], data['wind_direction'],
                     data['wind_speed_max'])
meteogram.plot_thermo(data['air_temperature'], data['dewpoint'])
meteogram.plot_rh(data['relative_humidity'])
meteogram.plot_pressure(data['mean_slp'])
fig.subplots_adjust(hspace=0.5)
plt.show()
Esempio n. 35
0
def Map_6hrPrecip(i, im_save_path):

    from siphon.catalog import TDSCatalog
    top_cat = TDSCatalog('http://thredds.ucar.edu/thredds/catalog.xml')
    ref_anl = top_cat.catalog_refs['Forecast Products and Analyses']
    new_cat_anl = ref_anl.follow()
    model_anl = new_cat_anl.catalog_refs[1]
    gfs_anl_cat = model_anl.follow()
    ds_anl = gfs_anl_cat.datasets[1]

    subset = ds_anl.subset()
    query_data = subset.query()
    query_data.lonlat_box(west=-130, east=-50, south=10, north=60)

    # Allow for NetCDF files
    query_data.accept('netcdf4')
    query_data.time(i)
    data = query_data.variables(
        "Total_precipitation_surface_6_Hour_Accumulation").add_lonlat()

    # Finally attempt to access the data
    data = subset.get_data(query_data)
    dew = data.variables[
        'Total_precipitation_surface_6_Hour_Accumulation'][:].squeeze()
    dew = np.ma.masked_where(dew < 2., dew)

    lat = data.variables['lat'][:].squeeze()
    lon = data.variables['lon'][:].squeeze()
    #lats = data.variables['lat'][:]
    #lons = data.variables['lon'][:]
    time_var = data.variables[find_time_var(
        data.variables['Total_precipitation_surface_6_Hour_Accumulation'])]

    # Convert number of hours since the reference time into an actual date
    time_final = num2date(time_var[:].squeeze(), time_var.units)
    print(
        str(time_final)[:4] + "_" + str(time_final)[5:7] + "_" +
        str(time_final)[8:10] + "_" + str(time_final)[11:13] + "Z")
    file_time = str(time_final)[:4] + "_" + str(time_final)[5:7] + "_" + str(
        time_final)[8:10] + "_" + str(time_final)[11:13] + "Z"

    # Create new figure
    fig = plt.figure(figsize=(17., 11.))

    add_metpy_logo(fig, 30, 1000, size='small')

    # Add the map and set the extent
    ax = plt.subplot(111, projection=plotcrs)

    #Set the lat and lon boundaries
    ax.set_extent(extent, datacrs)

    # Add state boundaries to plot
    ax.add_feature(states_provinces, edgecolor='blue', linewidth=1)

    # Add country borders to plot
    ax.add_feature(country_borders, edgecolor='black', linewidth=1)

    # Plot Title
    plt.title('6-hr Precip Accumulation ($kg/m^{2}$)',
              loc='left',
              fontdict=font)
    plt.title(' {0:%d %B %Y %H:%MZ}'.format(time_final),
              loc='right',
              fontdict=font)

    cs = ax.contourf(lon, lat, dew, 40, cmap="jet",
                     transform=datacrs)  #norm=Normalize(-1, 80)
    cbaxes = fig.add_axes(colorbar_axis)  # [left, bottom, width, height]
    cbar = plt.colorbar(cs, orientation='horizontal', cax=cbaxes)
    #cbar.set_label(r'$s^-1$')

    #plt.show()
    plt.close(fig)
    #---------------------------------------------------------------------------------------------------
    #---------------------------------------------------------------------------------------------------
    PV_Jet = im_save_path + "GFS/Precip_6/"
    if not os.path.isdir(PV_Jet):
        os.makedirs(PV_Jet)
    fig.savefig(PV_Jet + "Precip_Accum" + file_time + ".png",
                bbox_inches='tight',
                dpi=120)

    print('done.')
Esempio n. 36
0
"""
NEXRAD Level 3 File
===================

Use MetPy to read information from a NEXRAD Level 3 (NIDS product) file and plot
"""
import matplotlib.pyplot as plt
import numpy as np

from metpy.cbook import get_test_data
from metpy.io import Level3File
from metpy.plots import add_metpy_logo, ctables

###########################################
fig, axes = plt.subplots(1, 2, figsize=(15, 8))
add_metpy_logo(fig, 1200, 85, size='large')
for v, ctable, ax in zip(('N0Q', 'N0U'), ('NWSReflectivity', 'NWSVelocity'), axes):
    # Open the file
    name = get_test_data('nids/KOUN_SDUS54_{}TLX_201305202016'.format(v), as_file_obj=False)
    f = Level3File(name)

    # Pull the data out of the file object
    datadict = f.sym_block[0][0]

    # Turn into an array, then mask
    data = np.ma.array(datadict['data'])
    data[data == 0] = np.ma.masked

    # Grab azimuths and calculate a range based on number of gates
    az = np.array(datadict['start_az'] + [datadict['end_az'][-1]])
    rng = np.linspace(0, f.max_range, data.shape[-1] + 1)
Esempio n. 37
0
###########################################
# We will pull the data out of the example dataset into individual variables and
# assign units.

p = df['pressure'].values * units.hPa
T = df['temperature'].values * units.degC
Td = df['dewpoint'].values * units.degC
wind_speed = df['speed'].values * units.knots
wind_dir = df['direction'].values * units.degrees
u, v = mpcalc.wind_components(wind_speed, wind_dir)

###########################################
# Create a new figure. The dimensions here give a good aspect ratio.

fig = plt.figure(figsize=(9, 9))
add_metpy_logo(fig, 115, 100)
skew = SkewT(fig, rotation=45)

# Plot the data using normal plotting functions, in this case using
# log scaling in Y, as dictated by the typical meteorological plot.
skew.plot(p, T, 'r')
skew.plot(p, Td, 'g')
skew.plot_barbs(p, u, v)
skew.ax.set_ylim(1000, 100)
skew.ax.set_xlim(-40, 60)

# Calculate LCL height and plot as black dot. Because `p`'s first value is
# ~1000 mb and its last value is ~250 mb, the `0` index is selected for
# `p`, `T`, and `Td` to lift the parcel from the surface. If `p` was inverted,
# i.e. start from low value, 250 mb, to a high value, 1000 mb, the `-1` index
# should be selected.
Esempio n. 38
0
                tlats,
                msf[level, :, :],
                clevmsf,
                colors='k',
                linewidths=1.0,
                linestyles='solid')
plt.clabel(cs,
           fontsize=10,
           inline=1,
           inline_spacing=7,
           fmt='%i',
           rightside_up=True,
           use_clabeltext=True)

# Add metpy logo
add_metpy_logo()

# Plot RH
cf = ax.contourf(tlons,
                 tlats,
                 isentrh[level, :, :],
                 range(10, 106, 5),
                 cmap=plt.cm.gist_earth_r)
cb = plt.colorbar(cf,
                  orientation='horizontal',
                  extend=max,
                  aspect=65,
                  shrink=0.5,
                  pad=0,
                  extendrect='True')
cb.set_label('Relative Humidity', size='x-large')
Esempio n. 39
0
# Map weather strings to WMO codes, which we can use to convert to symbols
# Only use the first symbol if there are multiple
wx = [wx_code_map[s.split()[0] if ' ' in s else s] for s in data['weather'].fillna('')]


###########################################
# The payoff
# ----------

# Change the DPI of the resulting figure. Higher DPI drastically improves the
# look of the text rendering.
plt.rcParams['savefig.dpi'] = 255

# Create the figure and an axes set to the projection.
fig = plt.figure(figsize=(20, 10))
add_metpy_logo(fig, 1080, 290, size='large')
ax = fig.add_subplot(1, 1, 1, projection=proj)

# Add some various map elements to the plot to make it recognizable.
ax.add_feature(cfeature.LAND)
ax.add_feature(cfeature.OCEAN)
ax.add_feature(cfeature.LAKES)
ax.add_feature(cfeature.COASTLINE)
ax.add_feature(cfeature.STATES)
ax.add_feature(cfeature.BORDERS)

# Set plot bounds
ax.set_extent((-118, -73, 23, 50))

#
# Here's the actual station plot
Esempio n. 40
0
def test_add_metpy_logo_large():
    """Test adding a large MetPy logo to a figure."""
    fig = plt.figure(figsize=(9, 9))
    add_metpy_logo(fig, size='large')
    return fig
Esempio n. 41
0
###########################################

# Open the GINI file from the test data
f = GiniFile(get_test_data('WEST-CONUS_4km_WV_20151208_2200.gini'))
print(f)

###########################################
# Get a Dataset view of the data (essentially a NetCDF-like interface to the
# underlying data). Pull out the data and (x, y) coordinates. We use `metpy.parse_cf` to
# handle parsing some netCDF Climate and Forecasting (CF) metadata to simplify working with
# projections.
ds = xr.open_dataset(f)
x = ds.variables['x'][:]
y = ds.variables['y'][:]
dat = ds.metpy.parse_cf('WV')

###########################################
# Plot the image. We use MetPy's xarray/cartopy integration to automatically handle parsing
# the projection information.
fig = plt.figure(figsize=(10, 12))
add_metpy_logo(fig, 125, 145)
ax = fig.add_subplot(1, 1, 1, projection=dat.metpy.cartopy_crs)
wv_norm, wv_cmap = colortables.get_with_range('WVCIMSS', 100, 260)
wv_cmap.set_under('k')
im = ax.imshow(dat[:], cmap=wv_cmap, norm=wv_norm,
               extent=(x.min(), x.max(), y.min(), y.max()), origin='upper')
ax.add_feature(cfeature.COASTLINE.with_scale('50m'))
add_timestamp(ax, f.prod_desc.datetime, y=0.02, high_contrast=True)

plt.show()
Esempio n. 42
0
def Map_1000_500(i, im_save_path):
    """
    i is the forecast time
    
    """

    from siphon.catalog import TDSCatalog
    top_cat = TDSCatalog('http://thredds.ucar.edu/thredds/catalog.xml')
    ref = top_cat.catalog_refs['Forecast Model Data']
    new_cat = ref.follow()
    model = new_cat.catalog_refs[4]
    gfs_cat = model.follow()

    ds = gfs_cat.datasets[1]
    subset = ds.subset()
    query_data = subset.query()
    query_data.lonlat_box(west=-130, east=-50, south=10, north=60)

    # Allow for NetCDF files
    query_data.accept('netcdf4')
    query_data.time(i)
    data = query_data.variables('Geopotential_height_isobaric')

    # Finally attempt to access the data
    data = subset.get_data(query_data)
    lat = data.variables['lat'][:].squeeze()
    lon = data.variables['lon'][:].squeeze()
    lev_500 = np.where(data.variables['isobaric4'][:] == 50000)[0][0]
    hght_500 = data.variables['Geopotential_height_isobaric'][0, lev_500, :, :]

    # Create a figure object, title it, and do the plots.
    fig = plt.figure(figsize=(17., 11.))

    add_metpy_logo(fig, 30, 940, size='small')

    # Add the map and set the extent
    ax5 = plt.subplot(1, 1, 1, projection=plotcrs)
    ax5.set_extent(extent, datacrs)

    # Add state boundaries to plot
    ax5.add_feature(states_provinces, edgecolor='k', linewidth=1)

    # Add country borders to plot
    ax5.add_feature(country_borders, edgecolor='black', linewidth=1)

    # Convert number of hours since the reference time into an actual date
    time_var = data.variables[find_time_var(
        data.variables['Geopotential_height_isobaric'])]
    time_final = num2date(time_var[:].squeeze(), time_var.units)
    print(
        str(time_final)[:4] + "_" + str(time_final)[5:7] + "_" +
        str(time_final)[8:10] + "_" + str(time_final)[11:13] + "Z")
    file_time = str(time_final)[:4] + "_" + str(time_final)[5:7] + "_" + str(
        time_final)[8:10] + "_" + str(time_final)[11:13] + "Z"

    # Plot Title
    plt.title('GFS: 1000 and 500mb Heights (m)', loc='left', fontdict=font)
    plt.title(' {0:%d %B %Y %H:%MZ}'.format(time_final),
              loc='right',
              fontdict=font)

    # Heights - 1000mb
    #---------------------------------------------------------------------------------------------------
    lev_1000 = np.where(data.variables['isobaric4'][:] == 100000)[0][0]

    hght_1000 = data.variables['Geopotential_height_isobaric'][0,
                                                               lev_1000, :, :]
    MIN = hght_1000.min()
    MAX = hght_1000.max()
    #print hght_1000.min(),hght_1000.max()
    hght_1000 = ndimage.gaussian_filter(hght_1000, sigma=3,
                                        order=0) * units.meter

    clev1000 = np.arange(MIN, MAX, 50)
    cs = ax5.contour(lon,
                     lat,
                     hght_1000.m,
                     clev1000,
                     colors='blue',
                     linewidths=2.0,
                     linestyles='solid',
                     transform=ccrs.PlateCarree())
    plt.clabel(cs,
               fontsize=10,
               inline=1,
               inline_spacing=10,
               fmt='%i',
               rightside_up=True,
               use_clabeltext=True)

    # Heights - 500mb
    #---------------------------------------------------------------------------------------------------
    MIN = hght_500.min()
    MAX = hght_500.max()
    #print hght_500.min(),hght_500.max()
    hght_500 = ndimage.gaussian_filter(hght_500, sigma=3,
                                       order=0) * units.meter

    clev500 = np.arange(MIN, MAX, 70)
    cs = ax5.contour(lon,
                     lat,
                     hght_500.m,
                     clev500,
                     colors='black',
                     linewidths=2.0,
                     linestyles='solid',
                     transform=ccrs.PlateCarree())
    plt.clabel(cs,
               fontsize=10,
               inline=1,
               inline_spacing=10,
               fmt='%i',
               rightside_up=True,
               use_clabeltext=True)

    #plt.show()
    plt.close(fig)
    #---------------------------------------------------------------------------------------------------
    #---------------------------------------------------------------------------------------------------

    GFS_1000_500 = im_save_path + "GFS/1000_500mb/"
    if not os.path.isdir(GFS_1000_500):
        os.makedirs(GFS_1000_500)
    fig.savefig(GFS_1000_500 + "1000_500mb_Heights_" + file_time + ".png",
                bbox_inches='tight',
                dpi=120)

    print('done.')
Esempio n. 43
0
def Map_Theta(i, im_save_path):
    from siphon.catalog import TDSCatalog
    top_cat = TDSCatalog('http://thredds.ucar.edu/thredds/catalog.xml')
    ref = top_cat.catalog_refs['Forecast Model Data']
    new_cat = ref.follow()
    model = new_cat.catalog_refs[4]
    gfs_cat = model.follow()
    ds = gfs_cat.datasets[1]
    subset = ds.subset()
    query_data = subset.query()
    query_data.lonlat_box(west=-130, east=-50, south=10, north=60)

    # Allow for NetCDF files
    query_data.accept('netcdf4')
    query_data.time(i)
    data = query_data.variables("Potential_temperature_sigma",
                                "Pressure_reduced_to_MSL_msl",
                                "u-component_of_wind_height_above_ground",
                                "v-component_of_wind_height_above_ground")

    # Finally attempt to access the data
    data = subset.get_data(query_data)

    theta = data.variables['Potential_temperature_sigma'][:].squeeze()
    mslp = data.variables['Pressure_reduced_to_MSL_msl'][:] * units.Pa
    mslp.ito('hPa')
    mslp = gaussian_filter(mslp[0], sigma=3.0)
    u_wind = units('m/s') * data.variables[
        'u-component_of_wind_height_above_ground'][:].squeeze()
    v_wind = units('m/s') * data.variables[
        'v-component_of_wind_height_above_ground'][:].squeeze()
    u_wind.ito('kt')
    v_wind.ito('kt')
    lev_10m = np.where(data.variables['height_above_ground3'][:] == 10)[0][0]
    u_wind_10m = u_wind[lev_10m]
    v_wind_10m = v_wind[lev_10m]

    lat = data.variables['lat'][:]
    lon = data.variables['lon'][:]
    # Create a figure object, title it, and do the plots.
    fig = plt.figure(figsize=(17., 11.))

    add_metpy_logo(fig, 30, 940, size='small')

    # Add the map and set the extent
    ax = plt.subplot(1, 1, 1, projection=plotcrs)

    # Add state boundaries to plot
    ax.add_feature(states_provinces, edgecolor='b', linewidth=1)

    # Add country borders to plot
    ax.add_feature(country_borders, edgecolor='k', linewidth=1)

    # Convert number of hours since the reference time into an actual date
    time_var = data.variables[find_time_var(
        data.variables['Potential_temperature_sigma'])]
    time_final = num2date(time_var[:].squeeze(), time_var.units)
    print(
        str(time_final)[:4] + "_" + str(time_final)[5:7] + "_" +
        str(time_final)[8:10] + "_" + str(time_final)[11:13] + "Z")
    file_time = str(time_final)[:4] + "_" + str(time_final)[5:7] + "_" + str(
        time_final)[8:10] + "_" + str(time_final)[11:13] + "Z"

    # Plot Title
    plt.title('GFS: Potential Temperature (K)', loc='left', fontsize=16)
    plt.title(' {0:%d %B %Y %H:%MZ}'.format(time_final),
              loc='right',
              fontsize=16)

    # Dew Points
    #---------------------------------------------------------------------------------------------------
    levs = np.arange(50, 5000, 100)
    cs = ax.contour(lon,
                    lat,
                    theta,
                    30,
                    cmap="nipy_spectral",
                    transform=datacrs)
    #plt.clabel(cs, fontsize=10, inline=1, inline_spacing=10, fmt='%i',
    #           rightside_up=True, use_clabeltext=True)

    cbaxes = fig.add_axes(colorbar_axis)  # [left, bottom, width, height]

    cbar = plt.colorbar(cs, orientation='horizontal', cax=cbaxes)
    ax.set_extent(extent, datacrs)
    #ax.set_extent([-105, -98, 30, 50])

    kw_clabels = {
        'fontsize': 11,
        'inline': True,
        'inline_spacing': 5,
        'fmt': '%i',
        'rightside_up': True,
        'use_clabeltext': True
    }
    clevmslp = np.arange(800., 1120., 4)
    cs2 = ax.contour(lon,
                     lat,
                     mslp,
                     clevmslp,
                     colors='k',
                     linewidths=1.25,
                     linestyles='solid',
                     transform=datacrs)
    plt.clabel(cs2, **kw_clabels)

    # High and Low Symbols
    #---------------------------------------------------------------------------------------------------
    plot_maxmin_points(ax,
                       lon,
                       lat,
                       mslp,
                       'max',
                       50,
                       symbol='H',
                       color='b',
                       transform=datacrs)
    plot_maxmin_points(ax,
                       lon,
                       lat,
                       mslp,
                       'min',
                       25,
                       symbol='L',
                       color='r',
                       transform=datacrs)

    #---------------------------------------------------------------------------------------------------
    #---------------------------------------------------------------------------------------------------
    ax.barbs(lon,
             lat,
             u_wind_10m.magnitude,
             v_wind_10m.magnitude,
             length=6,
             regrid_shape=20,
             pivot='middle',
             transform=datacrs,
             barbcolor='k')

    GFS_theta = im_save_path + "GFS/Theta/"
    if not os.path.isdir(GFS_theta):
        os.makedirs(GFS_theta)
    fig.savefig(GFS_theta + "PotTemp_" + file_time + ".png",
                bbox_inches='tight',
                dpi=120)
    plt.close(fig)

    print('done.')