Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将降水数据绘制到matplotlib底图上_Python_Matplotlib Basemap_Netcdf4 - Fatal编程技术网

Python 将降水数据绘制到matplotlib底图上

Python 将降水数据绘制到matplotlib底图上,python,matplotlib-basemap,netcdf4,Python,Matplotlib Basemap,Netcdf4,灵感来自于Plot precip的例子,我想把昨天的降水数据绘制成一个图,投影到地图上。然而,由于降水数据的数据格式已发生变化,该网站的示例将不再使用 我的做法如下: from datetime import datetime, timedelta import netCDF4 import numpy as np import matplotlib.pyplot as plt import os.path import urllib from mpl_toolkits.basemap impo

灵感来自于Plot precip的例子,我想把昨天的降水数据绘制成一个图,投影到地图上。然而,由于降水数据的数据格式已发生变化,该网站的示例将不再使用

我的做法如下:

from datetime import datetime, timedelta
import netCDF4
import numpy as np
import matplotlib.pyplot as plt
import os.path
import urllib
from mpl_toolkits.basemap import Basemap

# set date for precipitation (1 day ago)
precip_date  = datetime.utcnow() - timedelta(days=1)
precip_fname = 'nws_precip_1day_{0:%Y%m%d}_conus.nc'.format( precip_date )
precip_url   = 'http://water.weather.gov/precip/downloads/{0:%Y/%m/%d}/{1}'.format( precip_date, precip_fname )

# download netCDF4-file if it does not exist already
if not os.path.isfile( precip_fname ):
    urllib.urlretrieve( precip_url, precip_fname )

# read netCDF4 dataset and extract relevant data
precip_dSet = netCDF4.Dataset( precip_fname )
# spatial coordinates
precip_x    = precip_dSet['x'][:]
precip_y    = precip_dSet['y'][:]
# precipitation data (is masked array in netCDF4-dataset)
precip_data = np.ma.getdata( precip_dSet['observation'][:] )
# grid information 
precip_lat0  = precip_dSet[ precip_dSet['observation'].grid_mapping ].latitude_of_projection_origin
precip_lon0  = precip_dSet[ precip_dSet['observation'].grid_mapping ].straight_vertical_longitude_from_pole
precip_latts = precip_dSet[ precip_dSet['observation'].grid_mapping ].standard_parallel
# close netCDF4 dataset
precip_dSet.close()

fig1, ax1 = plt.subplots(1,1, figsize=(9,6) )

# create the map
my_map = Basemap( projection='stere', resolution='l', 
                  width=(precip_x.max()-precip_x.min()), 
                  height=(precip_y.max()-precip_y.min()),
                  lat_0=30,                         # what is the correct value here?
                  lon_0=precip_lon0,
                  lat_ts=precip_latts
                )
# white background
my_map.drawmapboundary( fill_color='white' )
# grey coastlines, country borders, state borders
my_map.drawcoastlines( color='0.1' )
my_map.drawcountries( color='0.5' )
my_map.drawstates( color='0.8' )

# contour plot of precipitation data
# create the grid for the precipitation data
precip_lons, precip_lats = my_map.makegrid( precip_x.shape[0], precip_y.shape[0] )
precip_xx, precip_yy     = my_map( precip_lons, precip_lats ) 
# make the contour plot
cont_precip = my_map.contourf( precip_xx, precip_yy, precip_data )

plt.show()
  • 从国家气象局网站下载netCDF4文件
  • 打开netCDF4文件并提取相关信息
  • 使用
    Basemap
  • 将降水数据投影到地图上
  • 我想我的问题是我不理解netCDF4文件格式,尤其是元数据,因为降水数据的网格原点信息必须隐藏在其中的某个地方

    我的代码如下所示:

    from datetime import datetime, timedelta
    import netCDF4
    import numpy as np
    import matplotlib.pyplot as plt
    import os.path
    import urllib
    from mpl_toolkits.basemap import Basemap
    
    # set date for precipitation (1 day ago)
    precip_date  = datetime.utcnow() - timedelta(days=1)
    precip_fname = 'nws_precip_1day_{0:%Y%m%d}_conus.nc'.format( precip_date )
    precip_url   = 'http://water.weather.gov/precip/downloads/{0:%Y/%m/%d}/{1}'.format( precip_date, precip_fname )
    
    # download netCDF4-file if it does not exist already
    if not os.path.isfile( precip_fname ):
        urllib.urlretrieve( precip_url, precip_fname )
    
    # read netCDF4 dataset and extract relevant data
    precip_dSet = netCDF4.Dataset( precip_fname )
    # spatial coordinates
    precip_x    = precip_dSet['x'][:]
    precip_y    = precip_dSet['y'][:]
    # precipitation data (is masked array in netCDF4-dataset)
    precip_data = np.ma.getdata( precip_dSet['observation'][:] )
    # grid information 
    precip_lat0  = precip_dSet[ precip_dSet['observation'].grid_mapping ].latitude_of_projection_origin
    precip_lon0  = precip_dSet[ precip_dSet['observation'].grid_mapping ].straight_vertical_longitude_from_pole
    precip_latts = precip_dSet[ precip_dSet['observation'].grid_mapping ].standard_parallel
    # close netCDF4 dataset
    precip_dSet.close()
    
    fig1, ax1 = plt.subplots(1,1, figsize=(9,6) )
    
    # create the map
    my_map = Basemap( projection='stere', resolution='l', 
                      width=(precip_x.max()-precip_x.min()), 
                      height=(precip_y.max()-precip_y.min()),
                      lat_0=30,                         # what is the correct value here?
                      lon_0=precip_lon0,
                      lat_ts=precip_latts
                    )
    # white background
    my_map.drawmapboundary( fill_color='white' )
    # grey coastlines, country borders, state borders
    my_map.drawcoastlines( color='0.1' )
    my_map.drawcountries( color='0.5' )
    my_map.drawstates( color='0.8' )
    
    # contour plot of precipitation data
    # create the grid for the precipitation data
    precip_lons, precip_lats = my_map.makegrid( precip_x.shape[0], precip_y.shape[0] )
    precip_xx, precip_yy     = my_map( precip_lons, precip_lats ) 
    # make the contour plot
    cont_precip = my_map.contourf( precip_xx, precip_yy, precip_data )
    
    plt.show()
    
    这是输出的样子(是的,对于最终打印,必须调整颜色级别):


    我知道这是一个非常具体的问题,因此非常感谢任何建议/提示。

    如果我理解正确,您可以制作情节,但需要添加额外内容的提示吗

    xarray
    是处理netCDF文件的绝佳工具箱。它的工作原理类似于熊猫,但适用于netCDF文件,是对“netCDF4”的一大改进:

    要指定特定轮廓,可以输入标高:

     cont_precip = my_map.contourf( precip_xx, precip_yy, precip_data,levels=[10,20,30]) # Edit for exact contours needed
    
    如果需要,可以添加颜色栏:

    fig1.colorbar(cont_precip,ax=ax1)