I'm trying to plot GOES-East full disk data using metpy, and Siphon to download the latest data from the THREDDS data server. However, after comparing my plots with the realtime imagery, ther seems to be a large difference.
Below is my code:
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
import metpy.calc as mpcalc
from metpy.plots.ctables import registry
from metpy.plots import add_timestamp
from metpy.units import units
from siphon.catalog import TDSCatalog
import xarray as xr
import numpy as np
from xarray.backends import NetCDF4DataStore
from datetime import datetime, timedelta
dt = datetime.utcnow().date()
data = TDSCatalog(f'http://thredds.ucar.edu/thredds/catalog/satellite/goes/east/products/'
f'CloudAndMoistureImagery/FullDisk/Channel09/{dt:%Y%m%d}/catalog.xml')
sat_dataset = data.datasets[0].remote_access(use_xarray = True)
cmi = sat_dataset.metpy.parse_cf('Sectorized_CMI')
x = cmi.coords['x'][:]
y = cmi.coords['y'][:]
timestamp = datetime.strptime(str(cmi.time.values.astype('datetime64[s]')), '%Y-%m-%dT%H:%M:%S')
print(timestamp)
vtime = timestamp.strftime('%Y-%m-%d %H%M%S')
# Create the figure
fig = plt.figure(figsize = [16, 10])
ax = fig.add_subplot(1, 1, 1, projection = cmi.metpy.cartopy_crs)
ax.set_extent([-80, -45, -50, -15], crs = ccrs.PlateCarree())
ax.add_feature(cfeature.BORDERS.with_scale('50m'), edgecolor = 'black', linewidth = 1)
ax.add_feature(cfeature.COASTLINE.with_scale('50m'), edgecolor = 'black', linewidth = 1)
ax.add_feature(cfeature.STATES.with_scale('50m'), edgecolor = 'white', linewidth = 1)
# Add mapping information
ax.add_feature(cfeature.STATES)
ax.add_feature(cfeature.BORDERS, linewidth=2)
# Plot the image with our colormapping choices
wv_norm, wv_cmap = registry.get_with_range('WVCIMSS_r', 193, 283)
im = ax.imshow(cmi, extent=(x[0], x[-1], y[0], y[-1]), origin='upper',
cmap = wv_cmap, norm = wv_norm, transform = cmi.metpy.cartopy_crs)
plt.colorbar(im, ticks = np.arange(193, 293, 10), ax = ax)
plt.title(f'Vapor da Água em Níveis Médios [$K$] \nValid: {vtime} UTC', loc = 'left')
plt.savefig(f'/mnt/c/Users/vitor/Desktop/WV_{vtime}.jpg', bbox_inches = 'tight')
Also below, is a comparison between the output from my code and the actual water vapor imagery from the CODNEXLAB website. I also looked at the metadata of the downloaded files and everything seems to be fine. Not sure if I'm doing something wrong here.
What you're seeing is that your image is flipped (it's easier to identify if you look at the global plot of that data). What's happening is the origin you specified ('upper'/'lower') disagree with what you passed as extent. So either tweak your origin parameter:
im = ax.imshow(cmi, extent=(x[0], x[-1], y[0], y[-1]),
origin='lower', cmap=wv_cmap, norm=wv_norm,
transform=cmi.metpy.cartopy_crs)
or flip the order of your y extents:
im = ax.imshow(cmi, extent=(x[0], x[-1], y[-1], y[0]),
origin='upper', cmap=wv_cmap, norm=wv_norm,
transform=cmi.metpy.cartopy_crs)
Related
I´m trying to save my 3D trisurface Plot as an interactive HTML figure, so it should be possible to zoom in/ out and change the viewpoint. In the IDE the plot already exists and works so far, but I
can`t save it in the HTML format because of the ValueError:
"The fig parameter must be a dict or Figure.
Received value of type <class 'matplotlib.figure.Figure'>: Figure(1600x900)".
I don´t understand why the "<class 'matplotlib.figure.Figure'>" is not a Figure?
This was my approach: https://plotly.com/python/interactive-html-export/
And I tried it with go.Figure() (Export rotable 3D plots from Python to HTML) already but it didn´t work with the trisurf.
Is there a way to keep my Plot settings (use trisurf as it is) and get the interactive figure in HTML?
Thanks a lot for any answer
#Import libraries
import matplotlib
#matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator
import numpy as np
from mpl_toolkits.mplot3d import axes3d, Axes3D
import pandas as pd
import plotly.express as px
import io
import plotly.io as pio
%matplotlib notebook
E = np.arange(225)
D = np.arange(225)
A = np.arange(225)
E = [10000.0, 10000.0, ...]
D = [500.0, 1000.0, ...]
A = [1.9495, 1.9644, ...]
#Create figure
fig = plt.figure(figsize =(16, 9))
ax = plt.axes(projection ='3d')
# Creating color map
my_cmap = plt.get_cmap('hot')
# Data for three-dimensional scattered points
zdata = A
xdata = D
ydata = E
# Creating plot
trisurf = ax.plot_trisurf(xdata, ydata, zdata,
cmap = my_cmap,
linewidth = 0.2,
antialiased = True,
edgecolor = 'grey')
fig.colorbar(trisurf, ax = ax, shrink = 0.5, aspect = 10)
ax.set_title('AIE_SIM0.003__lowE_10000_upE_460000_stepE_30000_lowD_500.0_upD_8000.0_stepD_500.0')
ax.set_xlabel('Damping Ns/m')
ax.set_ylabel('Stifness N/m')
ax.set_zlabel('Amplification')
A2 = np.arange(225)
A2.fill(20.757)
# Creating color map
my_cmap2 = plt.get_cmap('gray')
# Data for three-dimensional scattered points
zdata2 = A2
xdata = D
ydata = E
# Creating plot
trisurf2 = ax.plot_trisurf(xdata, ydata, zdata2,
cmap = my_cmap2,
linewidth = 0.2,
antialiased = False,
edgecolor = 'none', alpha = 0.2)
fig.colorbar(trisurf2, ax = ax, shrink = 0.5, aspect = 10)
print(type(fig))
#fig.write_html("file.html")
plotly.io.to_html(fig=fig)
fig.savefig('3D_Plot_PNG_lowE_10000_upE_460000_stepE_30000_lowD_500.0_upD_8000.0_stepD_500.0.png')
fig.show()
------------------------------------------------------------------------------------------
Figure 1
printed: <class 'matplotlib.figure.Figure'>
ValueError:
The fig parameter must be a dict or Figure.
Received value of type <class 'matplotlib.figure.Figure'>: Figure(1600x900)
As far as I'm aware, Matplotlib is not able to generate 3D html plot.
Moreover, what you tried above is wrong. That error message is telling you that Plotly's to_html only works with Plotly's Figure. So mixing Plotly and Matplotlib is not going to work. You need to create a Plotly figure.
Also, I don't think that Plotly exposes something similar to Matplotlib's plot_trisurf. However, it exposes go.Mesh that allows us to achieve the same result.
The recipe:
Generate your numerical data.
Create a triangulation. We will use Matplotlib's Triangulation class for this part.
Create the Plotly figure and add the surface.
Export the figure to html.
Here I'm going to post an example to guide you:
import numpy as np
import matplotlib.tri as mtri
import plotly.graph_objects as go
### DATA GENERATION
# Make parameter spaces radii and angles.
n_angles = 36
n_radii = 8
min_radius = 0.25
radii = np.linspace(min_radius, 0.95, n_radii)
angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += np.pi/n_angles
# Map radius, angle pairs to x, y, z points.
x = (radii*np.cos(angles)).flatten()
y = (radii*np.sin(angles)).flatten()
z = (np.cos(radii)*np.cos(3*angles)).flatten()
### TRIANGULATION
# Create the Triangulation; no triangles so Delaunay triangulation created.
triang = mtri.Triangulation(x, y)
# Mask off unwanted triangles.
xmid = x[triang.triangles].mean(axis=1)
ymid = y[triang.triangles].mean(axis=1)
mask = xmid**2 + ymid**2 < min_radius**2
triangles = triang.triangles[~mask]
### PLOT
fig = go.Figure(data=[
# go.Mesh allows to provide the triangulation
go.Mesh3d(
x=x, y=y, z=z,
colorbar_title='z',
colorscale="aggrnyl",
# Intensity of each vertex, which will be interpolated and color-coded
intensity =z,
# i, j and k give the vertices of triangles
i = triangles[:, 0],
j = triangles[:, 1],
k = triangles[:, 2],
showscale=True
)
])
fig.show()
### EXPORT TO HTML
# Please, execute `help(fig.write_html)` to learn about all the
# available keyword arguments to control the output
fig.write_html("test.html", include_plotlyjs=True, full_html=True)
I have a set of data with (lon, lat, temperature) that I have plotted with Cartopy. The minimum example that I can give is the code below (with only 30 data points)
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
import matplotlib.colors as clr
import pandas as pd
import numpy as np
from metpy.interpolate import interpolate_to_grid, remove_nan_observations
from cartopy.io.shapereader import Reader
from cartopy.feature import ShapelyFeature
canada_east = -95
canada_west = -101.8
canada_north = 52.8
canada_south = 48.85
central_lon = (canada_east + canada_west)/2
central_lat = (canada_north + canada_south)/2
crs = ccrs.LambertConformal(central_longitude = central_lon, central_latitude = central_lat)
lat = np.array([49.8134 50.904 50.698 49.095 49.436 49.9607 49.9601 49.356 50.116
49.402 52.3472 50.411 49.24 49.876 49.591 49.905 49.498 49.088
49.118 50.5947 49.3776 49.148 49.1631 51.358 49.826 50.4324 49.96
49.68 49.875 50.829 51.572])
lon = np.array([-100.3721 -97.273 -99.068 -97.528 -100.308 -98.9054 -98.6367
-99.248 -96.434 -100.93 -101.1099 -100.893 -100.055 -99.909
-97.518 -99.354 -98.03 -99.325 -99.054 -98.0035 -100.5387
-100.491 -97.1454 -100.361 -96.776 -99.4392 -97.7463 -97.984
-95.92 -98.111 -100.488])
tem = np.array([-8.45 -4.026 -5.993 -3.68 -7.35 -7.421 -6.477 -8.03 -3.834
-13.04 -4.057 -8.79 -6.619 -10.89 -4.465 -8.41 -4.861 -9.93
-7.125 -4.424 -11.95 -9.56 -3.86 -7.17 -4.193 -7.653 -4.883
-5.631 -3.004 -4.738 -8.81])
xp, yp, _ = crs.transform_points(ccrs.PlateCarree(), lon, lat ).T
xp, yp, tem = remove_nan_observations(xp, yp, tem)
alt_x, alt_y, data = interpolate_to_grid( xp, yp, tem, minimum_neighbors=2, search_radius=240000, interp_type = 'barnes', hres = 1000)
# Create the figure and grid for subplots
fig = plt.figure(figsize=(17, 12))
# Main ax
ax = plt.subplot(111, projection=crs)
ax.set_extent([canada_west, canada_east, canada_south, canada_north], ccrs.PlateCarree())
# Ading province borders and country borders
provinces_bdr = cfeature.NaturalEarthFeature(category = 'cultural',
name = 'admin_1_states_provinces_lines',
scale = '50m',
linewidth = 0.6,
facecolor='none',
) # variable to add provinces border
country_bdr = cfeature.NaturalEarthFeature(category= 'cultural',
name = 'admin_0_boundary_lines_land',
scale = '50m',
linewidth = 1.5,
facecolor = 'none',
edgecolor = 'k')
ax.add_feature(provinces_bdr, linestyle='--')
ax.add_feature(country_bdr, linestyle='--')
ax.add_feature(cfeature.LAND)
ax.add_feature(cfeature.OCEAN)
ax.add_feature(cfeature.BORDERS)
cf = ax.pcolormesh(alt_x, alt_y, data, cmap=plt.cm.rainbow)
# Read the shape file and add it
shape_feature = ShapelyFeature(Reader('MB_AGregion_Perim_South.shp').geometries(), ccrs.epsg(26914), linewidth = 1, facecolor = (1, 1, 1, 0), edgecolor = (0.5, 0.5, 0.5, 1))
ax.add_feature(shape_feature)
plt.show()
which gives this result:
where the gray line inside is produced by the shape file. Now I want to limit the coloring to be only inside the shape file (so area that's outside of the gray line should not be colored by pcolormesh) but I can not find a way that work. I have read this example and this example but I cannot understand both of them. Is there a simple way to do this using geopandas and/or cartopy alone?
Sorry I cannot upload the shape file here, this is the best minimal example I could have done. If there are any improvements I should have done please tell me. I'm new to stack overflow and I'm open to critiques.
Edit1:
To clarify, the shape file I want the color to be limited to is the 'MB_AGregion_Perim_South.shp' that I read with ShapelyFeature (the last 4 lines of my code), and it draw the grey line that bounds most part of my coloring.
Edit 2:
As #Michael Delgado suggested, I have added this lines of code:
cat_gdf = geopandas.read_file('MB_AGregion_Perim_South.shp')
cat_gdf = cat_gdf.to_crs(epsg = 4326)
mask = shapely.vectorized.contains(cat_gdf.dissolve().geometry.item(), alt_x, alt_y)
where alt_x and alt_y is the interpolated result (please look at my example above). The shape file has epsg = 26914 originally, so I transform it into 4326.
The problem is that the mask contains all false values (which means it mask everything). I doubted that it's because alt_x and alt_y are coordinates that has been transformed with crs.transform_points(ccrs.PlateCarree(), lon, lat ).T (as my code showed above). I have search around and try to get the shape file into different epsg values but it doesn't work. Also, cat_gdf.geometry is a multi polygons. Could it be the cause here?
For anyone who's struggling with this in the future, here is a detailed explanation of the solution
Quick MRE:
import numpy as np, pandas as pd, geopandas as gpd
import matplotlib.pyplot as plt
x = np.arange(-126, -105, 0.1)
y = np.arange(25, 46, 0.1)
xx, yy = np.meshgrid(x, y)
xnorm = (xx - xx.min()) / (xx.max() - xx.min())
ynorm = (yy - yy.min()) / (yy.max() - yy.min())
v = np.cos((xnorm * 2 - 1) * np.pi) + np.sin((ynorm * 2 - 1) * np.pi)
gdf = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
fig, ax = plt.subplots()
ax.pcolormesh(xx, yy, v)
xlim, ylim = ax.get_xlim(), ax.get_ylim()
gdf.plot(ax=ax, color='none', edgecolor='k')
ax.set_xlim(*xlim)
ax.set_ylim(*ylim)
You can use shapely.vectorized to mask a set of x, y points using a shapely.geometry object:
import shapely.vectorized
mask = shapely.vectorized.contains(gdf.dissolve().geometry.item(), xx, yy)
fig, ax = plt.subplots()
ax.pcolormesh(xx, yy, np.where(mask, v, np.nan))
xlim, ylim = ax.get_xlim(), ax.get_ylim()
gdf.plot(ax=ax, color='none', edgecolor='k')
ax.set_xlim(*xlim)
ax.set_ylim(*ylim)
I was wondering if it's possible to plot all the steps from this single netcdf file into a separate plots.
Step 113 means that the current accessed data is for the date of October 22,2019. The Step 0 is July 1,2019. There are 135 time steps overall. Which means I need to produce 135 maps for each and single day.
#x,y,u,v for the maps
X=Data.longitude; Y=Data.latitude;
U=Data.u10[113]; V=Data.v10[113];
pm2p5=Data.pm2p5[113];
This is my code so far.
import xarray as xr
import cartopy.crs as ccrs
from cartopy import feature as cf
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
Data=xr.open_dataset('PMs ECMWF2.nc')
#x,y,u,v for the maps
X=Data.longitude; Y=Data.latitude;
U=Data.u10[113]; V=Data.v10[113];
pm2p5=Data.pm2p5[113];
nlon, nlat = np.meshgrid(X,Y)
fig, ax = plt.subplots(figsize=(12, 12), dpi=300)
# Add Plotting the plot
ax=plt.subplot(111,projection=ccrs.PlateCarree())
# Add Plot features
ax.add_feature(cf.BORDERS, linewidth=.5, edgecolor="yellow")
ax.coastlines('50m', linewidth=0.8)
ax.add_feature(cf.LAKES)
ax.add_feature(cf.OCEAN)
ax.add_feature(cf.BORDERS, edgecolor="yellow")
ax.add_feature(cf.COASTLINE, edgecolor="yellow")
ax.add_feature(cf.RIVERS)
ax.gridlines()
#changing the location of the map
ax.set_extent([90, 141, 24, -10])
# Add gridlines, and set their font size
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
linewidth=1, color='black', alpha=0.05, linestyle='-')
gl.top_labels = False
gl.left_labels = True
gl.right_labels = False
gl.xlines = True
gl.ylines = True
#colorbar
cmap = cm.get_cmap('jet') # Colour map coolwarm,hsv,bwr, seismic
# plotting the variables
pm2p5.plot(transform=ccrs.PlateCarree(), cbar_kwargs={'shrink': 0.5}, cmap=cmap)
plt.contour(nlon, nlat, pm2p5, fontsize=10,cmap=cmap) #plotting the contours
#plotting the quiver
ax.quiver(X[::3],Y[::3],U[::3,::3],V[::3,::3], color='white')
#plot title
#plt.title('Carbon Monoxide on October 22, 2019')
plt.show()
As of right now this code only produce one image. I have to do this over and over again.
One example of making a loop over time variable and maps of variable inside the loop, is here:
#!/usr/bin/env ipython
# ---------------------------
import numpy as np
from netCDF4 import Dataset,num2date
# ---------------------------
# let us generate data, preferably to the netcdf:
nx=50;ny=50;ntime=10;
A=np.random.random((ntime,ny,nx));
lon = np.linspace(0,360,nx);
lat = np.linspace(-90,90,ny);
time = np.linspace(0,366,ntime);timeunit = 'days since 2020-01-01 00:00:00'
fout = 'test.nc'
with Dataset(fout,'w') as f:
f.createDimension('longitude',nx);
f.createDimension('latitude',ny);
f.createDimension('time',);
xv = f.createVariable('longitude','float32',('longitude'));xv[:]=lon
yv = f.createVariable('latitude','float32',('latitude'));yv[:]=lat;
tv = f.createVariable('time','float32',('time'));tv[:]=time;tv.setncattr('units',timeunit);
u10 = f.createVariable('u10','float32',('time','latitude','longitude'));u10[:]=A;
v10 = f.createVariable('v10','float32',('time','latitude','longitude'));v10[:]=-A;
pm2 = f.createVariable('pm2p5','float32',('time','latitude','longitude'));pm2[:]=A;
# -----------------------------------------------
# let us now make some maps:
import xarray as xr
import cartopy.crs as ccrs
from cartopy import feature as cf
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
Data=xr.open_dataset(fout)
#x,y,u,v for the maps
X=Data.longitude; Y=Data.latitude;
time = Data.time;
for itime in range(len(time)):
U=Data.u10[itime]; V=Data.v10[itime];
pm2p5=Data.pm2p5[itime];
nlon, nlat = np.meshgrid(X,Y)
fig, ax = plt.subplots(figsize=(12, 12), dpi=300)
# Add Plotting the plot
ax=plt.subplot(111,projection=ccrs.PlateCarree())
# Add Plot features
ax.add_feature(cf.BORDERS, linewidth=.5, edgecolor="yellow")
ax.coastlines('50m', linewidth=0.8)
ax.add_feature(cf.LAKES)
ax.add_feature(cf.OCEAN)
ax.add_feature(cf.BORDERS, edgecolor="yellow")
ax.add_feature(cf.COASTLINE, edgecolor="yellow")
ax.add_feature(cf.RIVERS)
ax.gridlines()
#changing the location of the map
ax.set_extent([90, 141, 24, -10])
# Add gridlines, and set their font size
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
linewidth=1, color='black', alpha=0.05, linestyle='-')
gl.top_labels = False
gl.left_labels = True
gl.right_labels = False
gl.xlines = True
gl.ylines = True
#colorbar
cmap = cm.get_cmap('jet') # Colour map coolwarm,hsv,bwr, seismic
# plotting the variables
pm2p5.plot(transform=ccrs.PlateCarree(), cbar_kwargs={'shrink': 0.5}, cmap=cmap)
plt.contour(nlon, nlat, pm2p5, fontsize=10,cmap=cmap) #plotting the contours
#plotting the quiver
ax.quiver(X[::3],Y[::3],U[::3,::3],V[::3,::3], color='white')
#plot title
#plt.title('Carbon Monoxide on October 22, 2019')
plt.savefig('fig_'+str(itime).rjust(3,'0')+'.png',bbox_inches='tight');
plt.show();
# ----------------------------
I first generated a netCDF with random values and then plotted the variables for each time moment.
In the code, I have figured out the intersection point of two lines (22,50) and I want to show this in the graph (have an arrow pointing at the intersection point with (22,50)) and wondering if the community can help me with this.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from shapely.geometry import LineString
df = pd.read_csv("C:/Users/rajaa/Desktop/tril.csv")
t = df['time']
mu = df['material uts']
ps = df['pipe stress']
plt.figure(figsize = (8,5), dpi = 100)
fig, ax = plt.subplots()
plt.plot(t,mu,'r', label='Material UTS')
plt.plot(t,ps, 'b--',label=[enter image description here][1]'Pipe Stress as the pipe is depressurized')
plt.title('Graph 1', fontdict={'fontname': 'Arial', 'fontsize': 20})
plt.xticks(np.arange(0,32,2))
plt.yticks(np.arange(0,120,10))
plt.xlabel('Time (minutes)')
plt.ylabel('Pipe stress and UTS (MPa)')
plt.legend()
first_line = LineString(np.column_stack((t, mu)))
second_line = LineString(np.column_stack((t,ps)))
intersection = first_line.intersection(second_line)
plt.plot(*intersection.xy,'ro')
x,y = intersection.xy
plt.show()
ax.arrow(0, 0, 22, 50, head_width=0.05, head_length=0.1, fc='k', ec='k')
I am trying to plot separate maps for six different time steps of my data set. My code is shown below.
import matplotlib.pyplot as plt
import time
import cartopy.crs as ccrs
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
from cartopy.util import add_cyclic_point
import cartopy.feature as cfeature
from netCDF4 import Dataset
import numpy as np
#open dataset
myfile = 'gfs20191010.0p25.nc'
fh = Dataset(myfile, mode='r')
#select variables
h5001 = fh.variables['h5'][0:24,:,:]
h5002 = fh.variables['h5'][25:48,:,:]
h5003 = fh.variables['h5'][49:72,:,:]
h5004 = fh.variables['h5'][73:96,:,:]
h5005 = fh.variables['h5'][97:120,:,:]
h5006 = fh.variables['h5'][121:144,:,:]
lats = fh.variables['lat'][:]
lons = fh.variables['lon'][:]
#take mean of 500mb heights for the first 24 hours
day1 = np.mean(h5001,axis=0)
day2 = np.mean(h5002,axis=0)
day3 = np.mean(h5003,axis=0)
day4 = np.mean(h5004,axis=0)
day5 = np.mean(h5005,axis=0)
day6 = np.mean(h5006,axis=0)
fcst_crs = ccrs.PlateCarree()
fig = plt.figure(figsize=(5,5))
ax0 = plt.axes(projection=ccrs.PlateCarree())
ax0.set_extent([230,300,20,90],ccrs.PlateCarree())
ax0.coastlines()
ax0.add_feature(cfeature.BORDERS)
ax0.add_feature(cfeature.STATES)
ax0.set_title('Mean 500mb Heights (dam)', fontsize=12)
fig = plt.subplot(ax0)
mean1 = fig.contour(lons,lats,day1[0,:,:],levels=60,extend='both',transform=fcst_crs)
mean2 = fig.contour(lons,lats,day2[0,:,:],levels=60,extend='both',transform=fcst_crs)
mean3 = fig.contour(lons,lats,day3[0,:,:],levels=60,extend='both',transform=fcst_crs)
mean4 = fig.contour(lons,lats,day4[0,:,:],levels=60,extend='both',transform=fcst_crs)
mean5 = fig.contour(lons,lats,day5[0,:,:],levels=60,extend='both',transform=fcst_crs)
mean6 = fig.contour(lons,lats,day6[0,:,:],levels=60,extend='both',transform=fcst_crs)
fig1 = plt.contour(mean1, colors = 'black')
fig2 = plt.contour(mean2, colors = 'black')
fig3 = plt.contour(mean3, colors = 'black')
fig4 = plt.contour(mean4, colors = 'black')
fig5 = plt.contour(mean5, colors = 'black')
fig6 = plt.contour(mean6, colors = 'black')
plt.savefig('500mbHGT.png')
plt.show(fig1)
plt.show(fig2)
plt.show(fig3)
plt.show(fig4)
plt.show(fig5)
plt.show(fig6)
When I run the above code, all of my data plots on to one map. I have tried to make several adjustments based on the documentation provided here: https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.subplots.html
I've also tried following multiple examples of code using subplots for different uses. I am still unable to get separate maps plotted, but from what I understand, subplots is the way I should approach this problem, so hopefully I am on the right track.
By generating the subplots at the beginning with plt.subplots, for example:
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
fig, axes = plt.subplots(2, 1)
axes[0].set_title("Hammer projection")
map = Basemap(projection='hammer', lon_0 = 10, lat_0 = 50, ax=axes[0])
map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='coral',lake_color='aqua')
map.drawcoastlines()
axes[1].set_title("Robinson projection")
map = Basemap(projection='robin', lon_0 = 10, lat_0 = 50, ax=axes[1])
map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='coral',lake_color='aqua')
map.drawcoastlines()
plt.show()