Add functions and update of calc_ref_state.py to plot lat-lon fields

This commit is contained in:
Gabriel Wolf 2018-09-17 10:56:07 +01:00
parent 3b698337d6
commit 339af5e826
4 changed files with 462 additions and 1 deletions

View File

@ -9,6 +9,8 @@
import numpy as np #
import time # to measure elapsed time
from get_data import get_data_woa2009 as read_data
from myplot import myplot_2dmap # plot of lat-lon fields
from myplot_inputs import mycalc_create_pn # create plotname
# ############################################################################################
# Input 0 ####################################################################################
@ -23,7 +25,7 @@ print 'MANUAL DEFINED OUTPUTS MISSING'
dim = ('lon','lat','z','time',)
dir_plot = '/glusterfs/inspect/users/xg911182/Code/Python/plots_test/'
variables = {'s':{},'theta':{},'grd':[],'valid':[]}
lonlat_reg = [25.0, 25.0+360.0, -90.0, 90.0] # plotting range for 2dmap
# Input 1 ####################################################################################
# Physical constants
# input : None
@ -142,3 +144,36 @@ end_time = time.time()
print 'Elapsed time to plot and save reference state: '+ '{:.2f}'.format(end_time-beg_time)+'s'
print ' ----------------------------------------------'
# step g #####################################################################################
# plot of full 2d fields
# input : None
# output : None
# saved/created : plots saved in dir_plot
# dir_plot : output of Input 0
# ############################################################################################
beg_time = time.time()
print ''
print ' ----------------------------------------------'
print 'Insert code to plot full 2d fields'
# define plotname
list_allkeys = data.keys()
i_dep = 0
i_t = 0
date_str = '2009'
for i_key in range(0,len(list_allkeys)):
print 'put this plotname stuff into a function'
pname_str = mycalc_create_pn({'lonlat':lonlat_reg})
plotname_dum = dir_plot + 'Map2d_' + list_allkeys[i_key] + pname_str['lonlat'] + \
'_z' + str(grd.z[i_dep]) + grd.Uz + '_' + date_str + '.png'
# define plot input
title_in = 'Depth='+'{:.1f}'.format(grd.z[i_dep])+grd.Uz
data_in = data[list_allkeys[i_key]]['val'][:,:,i_dep,i_t]
data_in[data_in==data[list_allkeys[i_key]]['fill_value']] = np.nan
myplot_2dmap(data_in,grd,lonlat_range=lonlat_reg,saveplot=1,\
title_c=title_in,plotname=plotname_dum)
del data_in, title_in, pname_str,plotname_dum
print ' ----------------------------------------------'
end_time = time.time()
print 'Elapsed time to plot 2d fields (lat-lon): '+ '{:.2f}'.format(end_time-beg_time)+'s'
print ' ----------------------------------------------'

108
mycalc_matrix.py Normal file
View File

@ -0,0 +1,108 @@
def mymatrix_smooth(data_in,smooth_dim=(0,),data_per=(0,),window_len=3,window='step'):
# from mymatrix_operations import mymatrix_smooth
import numpy as np
from mymath import mymath_multiplylist
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# general input info %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
shape_data_in = data_in.shape
n_dim = len(shape_data_in)
# reshape matrix to get smoothing dimension into 0 and 1 dimension
rs_beg = np.array(range(0,n_dim))
rs_end = np.array(range(0,n_dim))
if n_dim > 1:
rs_beg[np.array([0,smooth_dim[0]])] = (smooth_dim[0],0)
if len(smooth_dim) > 1:
rs_beg[np.array([1,smooth_dim[1]])] = (rs_beg[smooth_dim[1]],rs_beg[1])
rs_end[np.array([1,smooth_dim[1]])] = (smooth_dim[1],1)
rs_end[np.array([0,smooth_dim[0]])] = (rs_end[smooth_dim[0]],rs_end[0])
# transpose data, so that smooth_dim are in the first two dimensions
data_in = data_in.transpose(rs_beg)
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# error checking %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if len(smooth_dim) > 2:
exit("smoothing only possible in two dimensions")
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# define window function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
window_len = int(window_len)
if window=='step':
window_num = np.ones(window_len/2+1);
elif window=='hanning':
window_num = (np.cos(np.array(range(0,window_len/2+1),dtype=float)/(window_len/2)*np.pi)+1)/2;
else:
print 'Defined window function not available for smoothing. No smoothing.'
window_num = 0;
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# create smoothing matrices for matrix multiplications %%%%%%%%%%%%%%%%%%%%%%
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Allocate smoothing matrix
if n_dim == 1:
smooth_ML = 1.
smooth_MR = np.zeros((shape_data_in[0],shape_data_in[0]),dtype=float)
np.fill_diagonal(smooth_MR[:], window_num[0])
else:
smooth_ML = np.zeros((shape_data_in[smooth_dim[0]],shape_data_in[smooth_dim[0]]),dtype=float)
if len(smooth_dim) > 1:
smooth_MR = np.zeros((shape_data_in[smooth_dim[1]],shape_data_in[smooth_dim[1]]),dtype=float)
np.fill_diagonal(smooth_MR[:], window_num[0])
else:
smooth_MR = 1.
np.fill_diagonal(smooth_ML[:], window_num[0])
# Fill smoothing matrix with window_num values
if n_dim == 1:
for i_d in range(1,window_len/2+1):
np.fill_diagonal(smooth_MR[i_d:], window_num[i_d])
np.fill_diagonal(smooth_MR[:,i_d:], window_num[i_d])
# modify smooth_matrix in case of periodic data
if data_per[0] == 1:
np.fill_diagonal(smooth_MR[(shape_data_in[0]-i_d):], window_num[i_d])
np.fill_diagonal(smooth_MR[:,(shape_data_in[0]-i_d):], window_num[i_d])
else:
for i_d in range(1,window_len/2+1):
np.fill_diagonal(smooth_ML[i_d:], window_num[i_d])
np.fill_diagonal(smooth_ML[:,i_d:], window_num[i_d])
# modify smooth_matrix in case of periodic data
if data_per[0] == 1:
np.fill_diagonal(smooth_ML[(shape_data_in[0]-i_d):], window_num[i_d])
np.fill_diagonal(smooth_ML[:,(shape_data_in[0]-i_d):], window_num[i_d])
if len(smooth_dim) > 1:
for i_d in range(1,window_len/2+1):
np.fill_diagonal(smooth_MR[i_d:], window_num[i_d])
np.fill_diagonal(smooth_MR[:,i_d:], window_num[i_d])
# modify smooth_matrix in case of periodic data
if data_per[1] == 1:
np.fill_diagonal(smooth_MR[(shape_data_in[1]-i_d):], window_num[i_d])
np.fill_diagonal(smooth_MR[:,(shape_data_in[1]-i_d):], window_num[i_d])
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# apply smoothing matrices to input data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if n_dim == 1:
data_in = data_in.dot(smooth_MR)
data_in = data_in/(np.ones(shape_data_in).dot(smooth_MR))
elif n_dim == 2:
data_in = smooth_ML.dot(data_in).dot(smooth_MR)
data_in = data_in/(smooth_ML.dot(np.ones(shape_data_in)).dot(smooth_MR))
else:
shape_data_in_new = (shape_data_in[0],shape_data_in[1],mymath_multiplylist(shape_data_in[2:]))
data_in = np.reshape(data_in,shape_data_in_new)
# loop over all other dimensions
for i_d in range(0,mymath_multiplylist(shape_data_in[2:])):
# smoothing in first dimension
if len(smooth_dim):
data_in[:,:,i_d] = smooth_ML.dot(data_in[:,:,i_d]).dot(smooth_MR)
data_in[:,:,i_d] = data_in[:,:,i_d]/(smooth_ML.dot(np.ones(shape_data_in[:2])).dot(smooth_MR))
data_in = np.reshape(data_in,shape_data_in)
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# define putput data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# transpose data back into original shape
data_in = data_in.transpose(rs_end)
return data_in

285
myplot.py Normal file
View File

@ -0,0 +1,285 @@
def myplot_1d(xxx,yyy,FS=22,trend=0,rm_yyy=0,yyy_per=0,col_c=('b','r','k'),label_c=('None'),xlabel_c='no xlabel info',ylabel_c='no ylabel info',saveplot=0,plotname='dummy.png',window='step'):
# from myplot import myplot_1d
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# input choices for myplot_1d %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# col_c=('b','r','k') : Default plotting colors, if more timeseries than num-
# ber of colors, a longer list of colors is necessary
# FS=[22] : Font Size for text, labels, etc
# label_c=('None') : Specification of lines in legend. To use no legend, set
# label_c=('None')
# plotname='dummy.png' : in case of saveplot=1, the plot will be saved under
# plotname (don't forget to include the path in plotname)
# rm_yyy=0 : window size (in data points) for smoothing, see further 'window'
# and yyy_per
# saveplot=0 : save the plotting? 1 for yes, 0 for no, see further plotname
# trend=0 : Include information about the trend of the timeseries (as text)
# window='step' : In case of smoothing (rm_yyy), this defines the window
# function used for smoothing. Available windows can be found in
# in my_matrix_operations.py under the function mymatrix_smooth
# xlabel_c='no xlabel info' : Text for xlabel
# ylabel_c='no ylabel info' : Text for ylabel
# yyy_per=0 : data periodic? (relevant for smoothing)
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# load modules and functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
from mymath import mymath_multiplylist
import numpy as np
import matplotlib.pyplot as plt
import math
from mycalc_matrix import mymatrix_smooth
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# data handling and specification
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# general data info
shape_yyy = yyy.shape
n_dim = len(shape_yyy)
if n_dim == 1:
yyy = np.tile(yyy,(2,1))
shape_yyy = yyy.shape
xxxmin = np.min(xxx); xxxmax = np.max(xxx); xxxd = xxxmax-xxxmin;
yyymin = np.min(yyy); yyymax = np.max(yyy); yyyd = yyymax-yyymin;
# smoothing of yyy
if rm_yyy > 0:
yyy_sm = [None] * mymath_multiplylist(shape_yyy)
yyy_sm = np.reshape(yyy_sm,shape_yyy)
for i_d in range(0,n_dim):
yyy_sm[i_d,:] = mymatrix_smooth(yyy[i_d,:],data_per=(yyy_per,),window_len=rm_yyy,window=window);
# calculate trend of input data
if trend == 1:
yyy_trend = [None] * n_dim
for i_d in range(0,n_dim):
yyy_trend_d = np.polyfit(xxx,yyy[i_d,:],1)
yyy_trend[i_d] = yyy_trend_d[0]
del yyy_trend_d
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# general plotting setup
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
mpl_fig = plt.figure(figsize=(24,8))
mpl_fig.patch.set_facecolor('w')
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# plotting (yyy)
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
line_data = [None] * n_dim
line_data_sm = [None] * n_dim
for i_d in range(0,n_dim):
if rm_yyy > 0:
line_data[i_d], = plt.plot(xxx,yyy[i_d,:],color=col_c[i_d],linestyle='-.',lw=2,label=label_c[i_d])
line_data_sm[i_d], = plt.plot(xxx,yyy_sm[i_d,:],color=col_c[i_d],linestyle='-',lw=2,label=label_c[i_d]+' (av='+str(rm_yyy)+'#,'+window+')')
else:
line_data[i_d], = plt.plot(xxx,yyy[i_d,:],color=col_c[i_d],linestyle='-',lw=2,label=label_c[i_d])
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# plotting (additional horizontal lines)
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i_d in range(0,n_dim):
plt.plot(xxx[[0,-1]],np.mean(yyy[i_d,:])*np.ones(2,'d'),color=col_c[i_d],lw=2)
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# include text
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# include trend information
if trend == 1:
exponent = int(math.floor(math.log10(abs(yyy_trend[0]))))
coeff = round(yyy_trend[0]/float(10**exponent),1)
if exponent==0:
trend_str = str(coeff)
else:
trend_str = str(coeff)+'x1e'+str(exponent)
if yyymax-np.mean(yyy)>np.mean(yyy[0,:])-yyymin:
plt.text(xxxmax-xxxd/5,yyymax-yyyd/20,'Trend: '+trend_str, fontsize=FS-2)
else:
plt.text(xxxmax-xxxd/5,yyymin+yyyd/80,'Trend: '+trend_str, fontsize=FS-2)
del coeff, exponent, trend_str
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# labeling, axis, etc
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
plt.ylabel(ylabel_c, fontsize=FS)
plt.xlabel(xlabel_c, fontsize=FS)
plt.xticks(fontsize=FS)
plt.yticks(fontsize=FS)
plt.xlim(xxxmin,xxxmax)
if yyymax-np.mean(yyy)>np.mean(yyy)-yyymin:
loc_c = 2
if rm_yyy > 0:
line_dummy = [None] * (n_dim*2)
line_dummy[0::2] = line_data
line_dummy[1::2] = line_data_sm
else:
line_dummy = line_data
else:
loc_c = 3
if rm_yyy > 0:
line_dummy = [None] * (n_dim*2)
line_dummy[0::2] = line_data
line_dummy[1::2] = line_data_sm
else:
line_dummy = line_data
plt.legend(handles=line_dummy,loc=loc_c, prop={'size': FS-4})
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# save plot
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if saveplot:
print 'save plot under: ' + plotname
plt.savefig(plotname,dpi=300,bbox_inches='tight')
else:
plt.show()
plt.close()
#def myplot_2dmap(xxx,yyy,FS=22,trend=0,rm_yyy=0,yyy_per=0,col_c=('b','r','k'),label_c=('None'),xlabel_c='no xlabel info',ylabel_c='no ylabel info',saveplot=0,plotname='dummy.png',window='step',title_c=[]):
def myplot_2dmap(data_in,grd,FS=22,plotname='dummy.png',saveplot=0,lonlat_range=[0.0,360.0,-90.0,90.0],\
xlabel_c=[],ylabel_c=[],title_c=[]):
# from myplot import myplot_2dmap
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# input choices for myplot_1d %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# data_in is the 2d field for plotting
# lonlat_range=[0.0,360.0,-90.0,90.0] : longitude/latitude range used for
# plotting
# plotname='dummy.png' : in case of saveplot=1, the plot will be saved under
# plotname (don't forget to include the path in plotname)
# saveplot=0 : save the plotting? 1 for yes, 0 for no, see further plotname
# FS=[22] : Font Size for text, labels, etc
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# load modules and functions
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
import numpy as np
import matplotlib.pyplot as plt
import math
from mycalc_matrix import mymatrix_smooth
from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid
# => cartopy instead of basemap
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# general plotting setup
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
mpl_fig = plt.figure(edgecolor='w',figsize=(18./360.*np.diff(lonlat_range[0:2]),12./180.*np.diff(lonlat_range[2:4])))
mpl_fig.patch.set_facecolor('w')
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# define map projection, include grid and map
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
mapproj = Basemap(projection='cyl',llcrnrlat=np.min(lonlat_range[2:4]), llcrnrlon=np.min(lonlat_range[0:2]),\
urcrnrlat=np.max(lonlat_range[2:4]), urcrnrlon=np.max(lonlat_range[0:2]))
mapproj.drawcoastlines()
mapproj.drawparallels(np.array([-90, -45, 0, 45, 90]),labels=[1,0,0,0])
mapproj.drawmeridians(np.array([0, 90, 180, 270, 360]),labels=[0,0,0,1])
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# redefine longitudes
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Create 2D lat/lon arrays for Basemap
for i_d in range(0,grd.Nlat):
data_in[:,i_d],lon_shift = shiftgrid(360.0*(np.min(lonlat_range[0:2])<0)+np.min(lonlat_range[0:2]), \
data_in[:,i_d], grd.lon, start=True, cyclic=360.0)
yyy, xxx = np.meshgrid(grd.lat,lon_shift)
#yyy, xxx = np.meshgrid(grd.lat,grd.lon)
#data_in,lon_shift = shiftgrid(360.0*(np.min(lonlat_range[0:2])<0)+np.min(lonlat_range[0:2]), \
# data_in, xxx, start=True, cyclic=360.0-np.mean(np.diff(grd.lon)))
lonall, latall = mapproj(xxx, yyy)
del yyy, xxx
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# plotting of data_in
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
mymapf = plt.contourf(lonall, latall, data_in, 10, cmap=plt.cm.Reds)
mymap = plt.contour(lonall, latall, data_in, 10, colors='k')
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# include contour labels, colorbar, etc.
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fmt_d = int(math.floor(np.max((0,-(np.log10(np.nanmean(data_in[:]))-2)))))
plt.clabel(mymap, fontsize=FS, colors='w', fmt='%.'+str(fmt_d)+'f')
del fmt_d
if title_c:
plt.title(title_c, fontsize=FS)
plt.colorbar(mymapf, orientation='horizontal', shrink=0.95)
#plt.colorbar(mymapf, orientation='horizontal', shrink=0.64)
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# labeling, axis, etc
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
plt.xticks(fontsize=FS)
plt.yticks(fontsize=FS)
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# save plot
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if saveplot:
print 'save plot under: ' + plotname
plt.savefig(plotname,dpi=300,bbox_inches='tight')
else:
plt.show()
plt.close()
del data_in, FS, plotname, lonlat_range
#def myplot_2d(xxx,yyy,FS=22,trend=0,rm_yyy=0,yyy_per=0,col_c=('b','r','k'),label_c=('None'),xlabel_c='no xlabel info',ylabel_c='no ylabel info',saveplot=0,plotname='dummy.png',window='step'):
def myplot_2d(xxx,yyy,zzz,FS=22,plotname='dummy.png',saveplot=0,xlabel_c=[],ylabel_c=[],\
d_xtick=[],cbarlabel_c=[],title_c=[],con_lines=[]):
# from myplot import myplot_2d
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# input choices for myplot_2d %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# zzz is the 2d field for plotting
# plotname='dummy.png' : in case of saveplot=1, the plot will be saved under
# plotname (don't forget to include the path in plotname)
# saveplot=0 : save the plotting? 1 for yes, 0 for no, see further plotname
# FS=[22] : Font Size for text, labels, etc
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# load modules and functions
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
import numpy as np
import matplotlib.pyplot as plt
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# general plotting setup
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
mpl_fig = plt.figure(edgecolor='w')
mpl_fig.patch.set_facecolor('w')
ax = plt.gca()
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# plotting of zzz
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#plt.pcolor(xxx,yyy,zzz,vmin=np.nanmin(zzz),vmax=np.nanmax(zzz))
mmm = np.ma.masked_where(np.isnan(zzz),zzz)
plt.pcolor(xxx,yyy,mmm,vmin=np.nanmin(zzz),vmax=np.nanmax(zzz))
ax.set_facecolor('gray')
#plt.imshow(zzz)
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# plotting additional contour lines
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if con_lines:
con_lines_val = con_lines['value']
for i_d in range(0,len(con_lines_val)):
plt.plot(con_lines_val[i_d][0],con_lines_val[i_d][1],con_lines['col'][i_d],label=con_lines['col'][i_d])
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# include contour labels, colorbar, etc.
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
cbar = plt.colorbar()
if cbarlabel_c:
cbar.set_label(cbarlabel_c, rotation=270, labelpad=10)
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# labeling, axis, etc
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if d_xtick:
xtick_c = np.arange(xxx.min()+d_xtick*(xxx.min()%d_xtick>0)-\
xxx.min()%d_xtick,xxx.max()-xxx.max()%d_xtick+d_xtick,d_xtick)
plt.xticks(xtick_c,fontsize=FS)
del xtick_c
else:
plt.xticks(fontsize=FS)
plt.yticks(fontsize=FS)
if ylabel_c:
plt.ylabel(ylabel_c, fontsize=FS)
if xlabel_c:
plt.xlabel(xlabel_c, fontsize=FS)
if title_c:
plt.title(title_c, fontsize=FS)
# set axis range
plt.xlim((xxx.min(),xxx.max()))
plt.ylim((yyy.min(),yyy.max()))
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# save plot
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if saveplot:
print 'save plot under: ' + plotname
plt.savefig(plotname,dpi=300,bbox_inches='tight')
else:
plt.show()
plt.close()
del FS, plotname

33
myplot_inputs.py Normal file
View File

@ -0,0 +1,33 @@
def mycalc_create_pn(dict_in):
# Allocation
pname_str = {}
# check if restriction to region exist
list_allkeys = dict_in.keys()
if 'lonlat' in list_allkeys:
dummy = dict_in['lonlat']
if dummy[0] < 0:
pn1 = '{:03d}'.format(int(abs(round(dummy[0])))) + 'W'
elif dummy[0] > 360:
pn1 = '{:03d}'.format(int(round(dummy[0])-360)) + 'E'
else:
pn1 = '{:03d}'.format(int(round(dummy[0]))) + 'E'
if dummy[1] < 0:
pn2 = '{:03d}'.format(int(abs(round(dummy[1])))) + 'W'
elif dummy[1] > 360:
pn2 = '{:03d}'.format(int(round(dummy[1])-360)) + 'E'
else:
pn2 = '{:03d}'.format(int(round(dummy[1]))) + 'E'
if dummy[2] < 0:
pn3 = '{:02d}'.format(int(abs(round(dummy[2])))) + 'S'
else:
pn3 = '{:02d}'.format(int(round(dummy[2]))) + 'N'
if dummy[3] < 0:
pn4 = '{:02d}'.format(int(abs(round(dummy[3])))) + 'S'
else:
pn4 = '{:02d}'.format(int(round(dummy[3]))) + 'N'
pname_str['lonlat'] = '_reg' + pn1 + 'to' + pn2 + pn3 + 'to' + pn4
del dummy
del dict_in, list_allkeys
return pname_str