dedent函数在Matplotlib 3.1中已弃用,在3.3中将被删除

时间:2019-06-18 00:32:56

标签: python python-3.x matplotlib matplotlib-basemap

我正在尝试将Goes-16 Netcdf文件投影到底图中,但是每次都遇到相同的错误。香港专业教育学院试图将python从3.7.3降级到3.6,更新和降级底图,而且我找不到任何有关此事的文献。

我在线阅读了python 3.7.3可能不再与底图兼容的信息,但是我之前使用python 3.7.1运行了代码,并且可以正常工作。我试图寻找代码中提到的替代方案“ inspect.cleandoc”,但我不知道如何正确使用该库。

我的代码是:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap 
import numpy as np
from remap import remap 
from cpt_convert import loadCPT 
from matplotlib.colors import LinearSegmentedColormap
from netCDF4 import Dataset
from matplotlib.patches import Rectangle
from osgeo import gdal



# Load the Data
# Path to the GOES-16 image file
channel_8 = 'C08/OR_ABI-L2-CMIPF-M3C08_G16_s20180391900384_e20180391911151_c20180391911220.nc'
path_30 = '/Volumes/Anthonys_backup/Masters_Thesis/Satellite_Data/new/'
path = path_30 + channel_8
High_q = 'yes'
geotif = 'no'
"Check remap.py!!!!!!!!"


nc = Dataset(path, 'r',)
H = nc.variables['goes_imager_projection'].perspective_point_height
#band = nc.variables['band_id'][:][0]
#Band = np.char.mod('%d', band)
Band = 8
# Choose the visualization extent (min lon, min lat, max lon, max lat)
extent = [-76, -60, -51, -20]

# Choose the image resolution (the higher the number the faster the processing is)
resolution = .1


# Call the reprojection funcion
grid = remap(path, extent, resolution, 'HDF5')

# Read the data returned by the function
if Band >= 7:
    data = grid.ReadAsArray()
    Unit = "Brightness Temperature [K]"
else:
    data = grid.ReadAsArray()
    a = data

    # set any negative values to zero\n"
    data[data < 0.] = 0.

    # normalize data to 1.16
    data = data/1.16

    # set any values greater than 1.0 equal to 1.0
    data[a>1.]=1.

    Unit = "Reflectance"


# Define the size of the saved picture
if High_q == 'yes':
    DPI = 150
    fig = plt.figure(figsize=(data.shape[1]/float(DPI), data.shape[0]/float(DPI)), 
                 frameon=False, dpi=DPI)
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    fig.add_axes(ax)
    ax = plt.axis('off')
else:
    DPI = 150

# Plot the Data 
# Create the basemap reference for the Rectangular Projection
bmap = Basemap(resolution='h', llcrnrlon=extent[0], llcrnrlat=extent[1], urcrnrlon=extent[2], urcrnrlat=extent[3], epsg=4326)

# Draw the countries and Argentinian states shapefiles
bmap.readshapefile('/Users/anthonycrespo/Desktop/New_code_for_plotting/arg_adm1/ARG_adm1','ARG_adm1',linewidth=.5,color='black')
bmap.readshapefile('/Users/anthonycrespo/Desktop/New_code_for_plotting/Countries_Shape/ne_10m_admin_0_countries','ne_10m_admin_0_countries',linewidth=.7,color='black')

# Draw parallels and meridians
bmap.drawcoastlines(linewidth=1., linestyle='solid', color='black')

bmap.drawparallels(np.arange(-90.0, 90.0, 3.), linewidth=0.3,
                       dashes=[4, 4], color='white', labels=[True,
                       True, False, False], fmt='%g', labelstyle="+/-",
                       xoffset=0.10, yoffset=-1.00, size=5)
bmap.drawmeridians(np.arange(0.0, 360.0, 3.), linewidth=0.3,
                       dashes=[4, 4], color='white', labels=[False,
                       False, True, False], fmt='%g', labelstyle="+/-",
                       xoffset=-0.80, yoffset=0.20, size=5)

# Converts a CPT file to be used in Python
if 7<= Band <= 10:
    cpt = loadCPT('/Users/anthonycrespo/Desktop/New_code_for_plotting/WVCOLOR35.cpt')
elif Band >= 11:
    cpt = loadCPT('/Users/anthonycrespo/Desktop/New_code_for_plotting/IR4AVHRR6.cpt')
else:
    pass

# Makes a linear interpolation
if Band >= 7:
    cpt_convert = LinearSegmentedColormap('cpt', cpt)
else:
    pass

# Plot the GOES-16 channel with the converted CPT colors
if Band >= 8:
    bmap.imshow(data, origin='upper', cmap=cpt_convert, vmin=170, vmax=378)
else:
    bmap.imshow(data, origin='upper', cmap='Greys_r', vmin=0., vmax=1.)


# Date and time
import datetime

time_var = nc.time_coverage_start
iyear = time_var[0:4]
imonth = time_var[5:7]

import calendar

cmonth = calendar.month_abbr[int(imonth)]
iday = time_var[8:10]
itime = time_var[11:19]
itimehr = time_var[11:13]
itimemn = time_var[14:16]

ctime_string = iyear +' '+cmonth+' '+iday+'  '+itime+' UTC'
ctime_file_string = iyear + imonth + iday + itimehr + itimemn

filestring = 'Channel 8' + iyear + imonth + iday + "_" + itimehr + itimemn + ".png"
filestring2 = 'CHANNEL 8' + iyear + imonth + iday + "_" + itimehr + itimemn + ".tif"
time_string = 'GOES-16 ABI Band 8 %s '%ctime_string
name = "GOES-16 ABI Band 8"
Name = (name + ' ' + ' ' + ' ' + ' ' + Unit)
time_stamp = ("%s" %ctime_string)


# Add a black rectangle in the bottom to insert the image description
lon_difference = (extent[2] - extent[0]) # Max Lon - Min Lon
currentAxis = plt.gca()
currentAxis.add_patch(Rectangle((extent[0], extent[1]), lon_difference, 
                                lon_difference * 0.060, alpha=1, zorder=3, 
                                facecolor='black'))


# Add the image description inside the black rectangle
lat_difference = (extent[3] - extent[1]) # Max lat - Min lat
plt.text(extent[0], extent[1] + lat_difference * 0.005, Name,
         horizontalalignment='left', color = 'white', size=3)
plt.text(extent[2], extent[1] + lat_difference * 0.005, time_stamp, 
         horizontalalignment='right', color = 'white', size=3)

# Insert the colorbar at the right
cb = bmap.colorbar(location='bottom', size = '2%', pad = '-4%')
cb.outline.set_visible(False) # Remove the colorbar outline
cb.ax.tick_params(width = 0) # Remove the colorbar ticks
cb.ax.xaxis.set_tick_params(pad=-7.5) # Put the colobar labels inside the colorbar
cb.ax.tick_params(axis='x', colors='grey', labelsize=3)  # Change the color and size of the colorbar labels


# Show the plot
#plt.show()
plt.savefig('/Users/anthonycrespo/Desktop/New_code_for_plotting/Images/' + filestring, dpi=DPI, bbox_inches='tight', pad_inches=0)

# Export the result to GeoTIFF
if geotif == 'yes':
    driver = gdal.GetDriverByName('GTiff')
    driver.CreateCopy('/Users/anthonycrespo/Desktop/New_code_for_plotting/Geotif/' + filestring2, grid, 0)
else:
    pass

# Close the plot window
plt.close()

完整的错误消息是:

ERROR 5: GDALWarpOptions.Validate(): nBandCount=0, no bands configured!
- finished! Time: 0.00048089027404785156 seconds
Reprojection.py:75: MatplotlibDeprecationWarning: 
The dedent function was deprecated in Matplotlib 3.1 and will be removed in 3.3. Use inspect.cleandoc instead.
  bmap = Basemap(resolution='h', llcrnrlon=extent[0], llcrnrlat=extent[1], urcrnrlon=extent[2], urcrnrlat=extent[3], epsg=4326)
Reprojection.py:78: MatplotlibDeprecationWarning: 
The dedent function was deprecated in Matplotlib 3.1 and will be removed in 3.3. Use inspect.cleandoc instead.
  bmap.readshapefile('/Users/anthonycrespo/Desktop/New_code_for_plotting/arg_adm1/ARG_adm1','ARG_adm1',linewidth=.5,color='black')
Reprojection.py:79: MatplotlibDeprecationWarning: 
The dedent function was deprecated in Matplotlib 3.1 and will be removed in 3.3. Use inspect.cleandoc instead.
  bmap.readshapefile('/Users/anthonycrespo/Desktop/New_code_for_plotting/Countries_Shape/ne_10m_admin_0_countries','ne_10m_admin_0_countries',linewidth=.7,color='black')
Segmentation fault: 11

1 个答案:

答案 0 :(得分:4)

问题发布后不久,change for fixing this warning似乎已合并到母版中。

同时,如果您有权访问site-packages/mpl_toolkits/basemap/__init__.py,则可以将from matplotlib import __version__ as _matplotlib_version行替换为

try:
    from inspect import cleandoc as dedent
except ImportError:
    # Deprecated as of version 3.1. Not quite the same
    # as textwrap.dedent.
    from matplotlib.cbook import dedent

我意识到@ImportanceOfBeingErnest注释首先意味着警告不是问题,但如果有人由于网络搜索而遇到此问题(如我所做的那样),那么如果他们有答案将是很好的