Test/myplot.py

286 lines
14 KiB
Python

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