加载netCDF文件的底图windbarbs

时间:2015-12-02 03:40:43

标签: python numpy matplotlib matplotlib-basemap

我试图使用底图将风倒钩绘制到地图上。 我有两个netCDF文件,我之前使用的一个例子让我使用了压缩的numpy文件。有没有办法将netCDF转换为numpy?或者我只是经常压缩文件?我的错误是它没有正确读取文件。

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from IPython.display import Image
from IPython.core.display import HTML 
plt.clf()
#Initiate a Basemap instance with the Lambert Conformal Conic projection and the specified bounds and resolution arguments.  Draw states, coastlines, and countries on the map. 
m = Basemap  (projection='lcc',lon_0=-92,lat_0=38,llcrnrlat=23.5,urcrnrlat=50,llcrnrlon=-107,urcrnrlon=-71,resolution='l',area_thresh=1000)  #Makes map window
V =np.load('042711_V.nc') #Load uandv.npz, a zipped NumPy file
U =np.load('042711_U.nc') #Load uandv.npz, a zipped NumPy file
x =np.transpose(V['x']) #Load x locations from zipped NumPy array
y =np.transpose(V['y']) #Load y locations from zipped NumPy array
u =np.transpose(V['u']) #Load u-component of velocity from zipped NumPy array
v =np.transpose(V['v']) #Load v-component of velocity from zipped NumPy array
cs=plt.contour(h, levels = range(5400,6000,60), colors = 'black') #Create contour map
plt.clabel(cs,fmt= '%.0f', inline = True) #Add labels
speed = np.sqrt(u**2+v**2) #Create speeds array
plt.barbs(x,y,u,v,speed) #Plot the wind barbs
plt.title('Brian\'s First Basemap')
m.drawcoastlines(color='black') #Draw coastlines
m.drawstates(color='green') #Draw States
m.drawcountries(color='gray') #Draw Countries
parallels = np.arange(0.,90,5.) #Create latitude reference lines every 5°
m.drawparallels(parallels,labels=[1,0,0,0],fontsize=10) #Draw latitude lines on map with preferences
meridians = np.arange(180.,360.,5.) #Create longitude reference lines every 5°
m.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10) #Draw longitude on map with preferences
plt.show()
#plt.savefig('Lab7_fig2.png', format='png') #Save your figure.  You should get the figure below. 

#Image(url= "Lab7_fig2.png")

1 个答案:

答案 0 :(得分:0)

下面的例子说明了如何1)读取netCDF文件,2)将其保存为压缩的Numpy数组,以及3)如何读回这样的压缩数组。

import numpy as np
import netCDF4 as nc4

# Load example data:
nc = nc4.Dataset('drycblles.default.0000000.nc')
u = nc.variables["u"][:,:]

print(type(u), u.shape)

# Save array in .npz format:
np.savez('u.npz', u)

# Read the file back:
u_npz = np.load('u.npz')

# Get list of available arrays:
keys = u_npz.files
# Read the data (there is only one array):
u_2 = u_npz[keys[0]]

print(type(u_2), u_2.shape)
  

<class 'numpy.ndarray'> (8, 32)

     

<class 'numpy.ndarray'> (8, 32)

问题可能在于如何保存压缩的Numpy数组。例如。

np.savez('u.npz', u)

Numpy自动分配名称(键)arr_0arr_1等:

u_npz = np.load('u.npz')    
keys = u_npz.files
print(keys)
  

[&#39; arr_0&#39;]

可以为要保存的阵列提供名称,例如用:

np.savez('u.npz', u_component=u)

print(keys)会给你:

  

[&#39; u_component&#39;]

因此,根据用于保存.npz文件的方法,您必须将其读作:

u_2 = u_npz['arr_0']

u_2 = u_npz['u_component']