-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrms_plots.py
1602 lines (1326 loc) · 58.1 KB
/
rms_plots.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Created on Wed Sep 16 18:21:18 2015
@author: acrnrms
"""
import numpy as np
#from mpl_toolkits.basemap import Basemap #(not installed)
import matplotlib.pyplot as plt # for basic plotting
import mpl_toolkits as mpltk
import matplotlib.colors as col
from matplotlib.colors import from_levels_and_colors
import matplotlib.cm as cm
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import cartopy.util as cutil
############################################################################
#COLOR MAPS#################################################################
############################################################################
def register_rms_cmaps(cmap='all'):
"""create my personal colormaps with discrete colors and register them.
default is to register all of them. can also specify which one.
User defined:
bluegrayred19: default
blue0red19:
blue0red11giss: Mimicing GISS T-trends (used for hiatus studies)
bluegrayred9dark: Used for retreat/advance skill studies
bluegrayred11dark: Used for retreat/advance skill studies
"""
print 'registering cmaps'
#bluegrayred19#########
# blueish at top, gray in middle, reddish at bottom
colors = np.array([ [10,50,120], \
[15,75,165], \
[30,110,200],\
[60,160,240],\
[80,180,250],\
[130, 210, 255],\
[160, 230, 255],\
[190, 235, 255],\
[210, 245, 255],\
[200, 200, 200],\
[250, 240, 150],\
[255, 222, 100],\
[255, 192, 60], \
[255, 160, 0], \
[255, 96, 0], \
[255, 50, 0], \
[225, 20, 0], \
[192, 0, 0], \
[165, 0, 0]],\
dtype=float)/255
thecmap = col.ListedColormap(colors,'bluegrayred19')
cm.register_cmap(cmap=thecmap)
#blue0red19#########
# As bluegrayred19, but white in middle
colors = np.array([ [10,50,120], \
[15,75,165], \
[30,110,200],\
[60,160,240],\
[80,180,250],\
[130, 210, 255],\
[160, 230, 255],\
[190, 235, 255],\
[210, 245, 255],\
[255, 255, 255],\
[250, 240, 150],\
[255, 222, 100],\
[255, 192, 60], \
[255, 160, 0], \
[255, 96, 0], \
[255, 50, 0], \
[225, 20, 0], \
[192, 0, 0], \
[165, 0, 0]],\
dtype=float)/255
thecmap = col.ListedColormap(colors,'blue0red19')
cm.register_cmap(cmap=thecmap)
#bluegray0red20#########
# As bluegray0red20, but white added
colors = np.array([ [10,50,120], \
[15,75,165], \
[30,110,200],\
[60,160,240],\
[80,180,250],\
[130, 210, 255],\
[160, 230, 255],\
[190, 235, 255],\
[210, 245, 255],\
[255, 255, 255],\
[225, 225, 225],\
[250, 240, 150],\
[255, 222, 100],\
[255, 192, 60], \
[255, 160, 0], \
[255, 96, 0], \
[255, 50, 0], \
[225, 20, 0], \
[192, 0, 0], \
[165, 0, 0]],\
dtype=float)/255
thecmap = col.ListedColormap(colors,'blue0grayred20')
cm.register_cmap(cmap=thecmap)
#blue0red11giss#########
# blueish at top, white in middle, yellow and red at bottom
# Mimicing GISS temp colors, but yellow less looking like pee as Fyfe's request
colors = np.array([ [131,63,233], \
[71,137,252], \
[125,206,253],\
[165,250,255],\
[213,255,226],\
[255,255,255],\
[255,255,200],\
[255,210,27],\
[250,173,19],\
[255,0,0],\
[132,30,30]],\
dtype=float)/255.
thecmap = col.ListedColormap(colors,'blue0red11giss')
cm.register_cmap(cmap=thecmap)
#bluegrayred11dark#########
# blueish at top, gray in middle, reddish at bottom
# Adapted 11-class RdBu from colorbrewer2.org:
# Recipe:
# 1) 11-class Rdbu
# 2) Replace the white color with gray (colorblind friendly)
colors = np.array([ [5,48,97], \
[33,102,172], \
[67,147,195],\
[146,197,222],\
[209,229,240],\
[130,130,130],\
[253,219,199],\
[244,165,130],\
[214,96,77],\
[178,24,43],\
[103,0,31]],\
dtype=float)/255.
thecmap = col.ListedColormap(colors,'bluegrayred11dark')
cm.register_cmap(cmap=thecmap)
#bluegrayred9dark#########
# Adapted 11-class RdBu from colorbrewer2.org:
# Recipe:
# 1) Pick the 4 darkest and 4 lightest colors from 11-class Rdbu
# 2) Replace the 3 middle ones with a gray shading (colorblind friendly)
colors = np.array([ [5,48,97], \
[33,102,172], \
[67,147,195],\
[146,197,222],\
[130,130,130],\
[244,165,130],\
[214,96,77],\
[178,24,43],\
[103,0,31]],\
dtype=float)/255.
thecmap = col.ListedColormap(colors,'bluegrayred9dark')
cm.register_cmap(cmap=thecmap)
#sic#########
colors = np.array([[9, 60, 112],\
[255, 255, 255]],\
dtype=float)/255.
thecmap = col.ListedColormap(colors,'sic')
cm.register_cmap(cmap=thecmap)
#
register_rms_cmaps()
############################################################################
#AXIS FOR FIGURES###########################################################
############################################################################
###################################################
def make_bm(ax,
region='glob',latnps0=50,latsps0=-50.,lonps0=270.,
coastlinewidth=0.5,coastlinecolor='black',
landmask=False,oceanmask=False,
drawgrid=False,
landfillcol=[0.85,0.85,0.85],
oceanfillcol=np.array([176, 237, 245])/255.):
"""Make a basemap for latlon plot.
Parameters:
-----------
ax : [axis]
Subplot axis
*region* : ['glob' | string]
Region for the plots. Current options:
#GLOBAL:
'glob': Global, standard (cylindrical) projections
'glob_rob': Global, Robinson projection
#POLAR:
'nps': North Pole stereographic (latnps0,lonps0)
'sps': South Pole stereographic (latsps0,lonps0)
'nps2': As nps, but rectagle like NSIDC
'nps3': As nps2, but zoomed in
'baf' : zoom on Baffin
#SUBREGIONS:
'nh': NH, standard (cylindrical) projections
'tpo_na': Tropical Pacific Ocean + North America (cylindrical)
'atl': Atlantic (cylindrical)
'na': North Atlantic (cylindrical)
*latnps0* : [ *50.* | float ]
Latitude boundary for nps plots
*latsps0* : [ *-50.* | float ]
Latitude boundary for nps plots
*lonps0* : [ *270.* | float ]
Longitude centre for nps and sps plots
*coastlinewidth* : [ *0.5* | float ]
Coastline width
*coastlinecolor* : [ *'black'* | string ]
Coastline color
*landmask*: [ *'False'* | Boolean ]
If True: Fill continents and lakes with gray color
*oceanmask*: [ *'False'* | Boolean ]
If True: Drawmapboundary with coral color
*drawgrid*: [ *'False'* | Boolean ]
If True:Draw grid every 30 degrees
*landfillcol*=[ *[0.85,0.85,0.85]* | arry ]
Fill color of land if landmask=True
*oceanfillcol*=[ np.array([176, 237, 245])/255. | array ]
Fill color of land if oceanmask=True
Returns:
--------
bm: Basemap handle
"""
polythres=50
##########global
if region == 'glob': #latlon (cylindrical)
lat1=-90; lat2=90;lon1=-180; lon2=180
mapparams = dict(projection='cyl',llcrnrlat=lat1,urcrnrlat=lat2,\
llcrnrlon=lon1,urcrnrlon=lon2,resolution='c')
elif region == 'glob_rob':
mapparams = dict(projection='robin',lon_0=0,resolution='l')
##########Poles
elif region == 'nps': #North Pole stereographic
mapparams = dict(projection='npstere',boundinglat=latnps0,lon_0=lonps0,
resolution='c',round=True)
if latnps0==50: polythres=35
if latnps0==40: polythres=55
elif region == 'sps': #South Pole stereographic
mapparams = dict(projection='spstere',boundinglat=latsps0,lon_0=lonps0,
resolution='c',round=True)
polythres=10
elif region == 'nps2': # As nps, but rectagle like NSIDC # nsidc.org/data/polar_stereo/ps_grids.html
mapparams = dict(projection='stere',llcrnrlat=33.92,urcrnrlat=31.37,
llcrnrlon=279.26,urcrnrlon=102.34,lat_0=90,lon_0=135,
resolution='c')
elif region == 'nps3': #As nps2, but zoomed in
lat1=37; lat2=36.5;lon1=280;lon2=105;lat_0=90;lon_0=138
mapparams = dict(projection='stere',llcrnrlat=lat1,urcrnrlat=lat2,
llcrnrlon=lon1,urcrnrlon=lon2,lat_0=lat_0,lon_0=lon_0,
resolution='c')
elif region == 'baf': #As nps2, but zoomed in
lat1=50; lat2=80;lon1=-100; lon2=-40
mapparams = dict(projection='cyl',llcrnrlat=lat1,urcrnrlat=lat2,\
llcrnrlon=lon1,urcrnrlon=lon2,resolution='c')
##########Subregions
elif region == 'nh': # NH, standard (cylindrical) projections
lat1=0; lat2=90;lon1=0; lon2=360
mapparams = dict(projection='cyl',llcrnrlat=lat1,urcrnrlat=lat2,\
llcrnrlon=lon1,urcrnrlon=lon2,resolution='c')
elif region == 'tpo_na': #Tropical Pacific Ocean + North America (cylindrical)
lat1=-20; lat2=80;lon1=100; lon2=310
mapparams = dict(projection='cyl',llcrnrlat=lat1,urcrnrlat=lat2,\
llcrnrlon=lon1,urcrnrlon=lon2,resolution='c')
elif region == 'atl': #Tropical Pacific Ocean + North America (cylindrical)
lat1=-30; lat2=80;lon1=-100; lon2=10
mapparams = dict(projection='cyl',llcrnrlat=lat1,urcrnrlat=lat2,\
llcrnrlon=lon1,urcrnrlon=lon2,resolution='c')
elif region == 'na': #North Atlantic
lat1=0; lat2=80;lon1=-70; lon2=10
mapparams = dict(projection='cyl',llcrnrlat=lat1,urcrnrlat=lat2,\
llcrnrlon=lon1,urcrnrlon=lon2,resolution='c')
else:
print "Incorrect region. Global: glob, glob_rob"
print " Polar: nps, nps2 nps3 sps"
print " Subregions: nh tpo_na"
return -1
mapparams['ax'] = ax
#mapparams['area_thresh']=100000
#### make map
bm=Basemap(**mapparams)
#### fill colors
# landfillcol=[0.85,0.85,0.85]
# oceanfillcol=np.array([176, 237, 245])/255.
if landmask:
if oceanmask:
bm.fillcontinents(landfillcol,lake_color=oceanfillcol)
bm.drawmapboundary(fill_color=oceanfillcol)
else:
bm.fillcontinents(landfillcol)
#### Remove annoying rivers: http://stackoverflow.com/questions/14280312/world-map-without-rivers-with-matplotlib-basemap
coasts = bm.drawcoastlines(zorder=1,color='white',linewidth=0) #remove standard coastlines and get handles
coasts_paths = coasts.get_paths()
ipolygons = np.arange(polythres)
for ipoly in range(len(coasts_paths)):
r = coasts_paths[ipoly]
# Convert into lon/lat vertices
polygon_vertices = [(vertex[0],vertex[1]) for (vertex,code) in
r.iter_segments(simplify=False)]
px = [polygon_vertices[i][0] for i in xrange(len(polygon_vertices))]
py = [polygon_vertices[i][1] for i in xrange(len(polygon_vertices))]
if ipoly in ipolygons:
bm.plot(px,py,linewidth=coastlinewidth,zorder=3,color='black') # plot only larger lakes
elif landmask:
bm.plot(px,py,linewidth=coastlinewidth,zorder=4,color=landfillcol) # if landmask: fill in with landfillcol
# if no land mask: donot plot, otherwise
# this will show up on contourf plots
#### drawgrid
if drawgrid:
bm.drawparallels(np.arange(-90.,90.,30.),linewidth=0.2)
#bm.drawmeridians(np.arange(0.,360.,30.),linewidth=0.2)
return bm
############################################################################
def make_vax(ax,
region='glob',plevtop=10, force_xaxis=False,plog='True'):
"""Make vertical axis for lat,plev plots
Parameters:
-----------
ax : [axis]
Subplot axis
*region* : ['glob' | string]
Region for the plots. Current options:
'glob': [-90,90]
'nh': [0,90]
*plevtop* : [ *10.* | float ]
Top pressure level
Returns:
--------
Nothing
"""
if ax is None:
ax=plt.gca()
if region=='NH':
latmin=0
latmax=85
elif region=='glob':
latmin=-85
latmax=85
# X-axis
ax.set_xlim(latmin,latmax)
if region=='NH':
ax.set_xticks([0, 20, 40,60, 80])
if ax.is_last_row() or force_xaxis:
if region=='NH':
ax.set_xticklabels(('EQ', '20N', '40N', '60N','80N'))
else:
ax.set_xticklabels((''))
# Y-axis
if plog: ax.set_yscale('log')
ax.invert_yaxis()
ax.set_ylim(1000,plevtop)
#if plevtop==10:
ax.set_yticks([1000,500, 200, 100, 50, 20,10])
if ax.is_first_col():
ax.set_yticklabels((1000,500, 200, 100, 50,20,10))
ax.set_ylabel('Pressure')
else: ax.set_yticklabels((''))
# X+Y-axis
ax.tick_params(which = 'both', direction = 'out')
ax.minorticks_off()
############################################################################
#COLORPLOTS#################################################################
############################################################################
############################################################################
def add_cf(ax,x,y,fld,
clevs=None,
cint=None,cint0=None,coffset=0.,nclevspos=5,
cmap='blue0red19',cmapi=None,
plot_co=True,
latlon=True):
"""add contourf plot to axis.
Parameters:
-----------
ax : [axis]
Either the basemap (latlon) or figure axis (latpres)
x : [array]
A 1D array with x-dimensions (lon or lat)
y : [array]
A 1D array with y-dimensions (lat or plev)
fld : [array]
A 2D array with the data to be plotted
*clevs* : [ *None* | array or list]
A 1D array or list with clevs
*cint0* : [ *None* | float]
Contour interval value used to create clevs centred around 0
*cint* : [ *None* | float]
Contour interval value used to create clevs that (includes 0)
*coffset* : [ *0* | float]
Offset for creating clevs from cint
*nclevspos* : [ *5* | int]
Number of positive contour levels, used to Contour interval value
used to create clevs that include 0
*cmap* : [ *'blue0red19'* | string ]
blue0red19: default
bluegrayred19:
blue0red11giss: Mimicing GISS T-trends (used for hiatus studies)
bluegrayred9dark: Used for retreat/advance skill studies
bluegrayred11dark: Used for retreat/advance skill studies
*cmapi* [ *None* | list ]
list of color indices
*plot_co*: [ *True | boolean ]
If True (default) plot contour
Returns:
--------
cf: contourf handle (typically to add colorbar after func call)
Notes:
--------
Contourf is more flexible than pcolormesh in the sense that it can
automap colors once you specify clevs.
Therefore, it supports nclevspos if cint is specified
"""
##### Determine if latlon, and make grid
#if np.max(x)>90 and np.max(y)<359: #X is lon (not lat), Y is lat (not pres)
if latlon==True:
# Add cyclic lon if needed
if np.mod(x.shape,2) == 0:
fld,x = mpltk.basemap.addcyclic(fld,x)
if np.max(y)<90:
fld,y =add_poles(fld,y)
xs,ys=np.meshgrid(x,y)
cfparams={'latlon':latlon}
#############clevs and colors###################################
cfparams['extend']='both'
if cmapi is not None: # clevs have to be given, manual mapping
if clevs is None:
print 'Error: when cmapi defined, clevs have to be defined too'
return -1
elif cint is not None or cint0 is not None:
print 'Error: when cmapi defined, cint/cint0 cannot be defined'
return -1
else:
colors=plt.get_cmap(cmap)(cmapi)
cmap, norm = from_levels_and_colors(clevs, colors ,extend='both')
cfparams['cmap']=cmap
cfparams['norm']=norm
cfparams['levels']=clevs
else: # automatically mapping
cfparams['cmap']=cmap
if clevs is not None:
cfparams['levels']=clevs
if cint0 is not None: #create clevs centred around 0
crange=(nclevspos-0.5)*cint0;
cmin=-crange+coffset; cmax=crange+coffset
cfparams['levels']=np.arange(cmin,cmax+cint0,cint0);
if cint is not None:#create clevs that includes 0
crange=nclevspos*cint;
cmin=-crange+coffset; cmax=crange+coffset
cfparams['levels']=np.arange(cmin,cmax+cint,cint);
#cfparams['zorder']=2
#############plot######################
cf=ax.contourf(xs,ys,fld,**cfparams)
if plot_co:
add_co(ax,x,y,fld,
clevs=clevs,cint=cint,cint0=cint0,coffset=coffset,
color='gray',linewidth=0.2,neg_dash=False)
return cf
############################################################################
def add_pc(ax,x,y,fld,
clevs=None,
cint=None,cint0=None,coffset=0.,
cmap='blue0red19',cmapi=None,extend='both'):
"""add pcolormesh to axis.
Parameters:
-----------
ax : axis
Either the basemap (latlon) or figure axis (latpres)
x : array
A 1D array with x-dimensions (lon or lat)
y : array
A 1D array with y-dimensions (lat or plev)
fld : array
A 2D array with the data to be plotted
*clevs* : [ *None* | array or list]
A 1D array or list with clevs
*cint0* : [ *None* | float]
Contour interval value used to create clevs centred around 0
*cint* : [ *None* | float]
Contour interval value used to create clevs (includes 0)
*coffset* : [ *0* | float]
Offset for creating clevs from cint
*cmap* : [ *'blue0red19'* | string ]
blue0red19: default
bluegrayred19:
blue0red11giss: Mimicing GISS T-trends (used for hiatus studies)
bluegrayred9dark: Used for retreat/advance skill studies
bluegrayred11dark: Used for retreat/advance skill studies
*cmapi* [ *None* | list ]
list of color indices
*extend* [ *both* | neither ]
Colorbar that extends beyond upper limit
Returns:
--------
pc: pcolormesh handle (typically to add colorbar after func call)
Notes:
--------
For pcolormesh, clevs not given explicitely, but through 'norm'
Therefore, if clevs/cint/cint0 given, we have to manually map
In case of specified cint/cint0, the range is determined by the ncolor in the cmap
Known issues/bugs:
--------
1) For lat,pres plot, have to shift the data
2) Error if basemap is 'glob'
"""
##### Determine if latlon, and make grid
if np.max(x)>90 and np.max(y)<359: #X is lon (not lat), Y is lat (not pres)
# Add cyclic lon if needed
if np.mod(x.shape,2) == 0:
fld,x = mpltk.basemap.addcyclic(fld,x)
lon_edge,lat_edge=centre_to_edge(x,y)
xs, ys = np.meshgrid(lon_edge,lat_edge) ###NB: len(lat_edge)=nlat+1
latlon=True
else: #lat,plev plot
latlon=False
xs,ys=np.meshgrid(x,y)
fld = np.ma.masked_invalid(fld) #http://stackoverflow.com/questions/7778343/pcolormesh-with-missing-values
#############colors #########
if cmapi is not None: # create colors from cmapi
colors=make_colors(cmap,cmapi)
else: # chose all colors from cmapi
colors=make_colors(cmap)
if cint is not None: # remove the middle color if clevs include 0
ncolors=np.shape(colors)[0]
ncolorsmin=int(np.floor(ncolors/2.))
colors=make_colors(cmap,range(ncolorsmin)+range(ncolorsmin+1,ncolors))
#############clevs######################################
ncolors=np.shape(colors)[0]
if clevs is not None:
clevs=np.asarray(clevs)
if cint:
crange=cint*(ncolors/2.-1);
clevs=np.linspace(-crange,crange,num=ncolors-1,endpoint=True)+coffset;
if cint0:
crange=cint0*(ncolors/2.-1);
clevs=np.linspace(-crange,crange,num=ncolors-1,endpoint=True)+coffset;
###########color mapping#####################################
if clevs is not None:
cmap, norm = from_levels_and_colors(clevs, colors ,extend=extend)
pcparams=dict(cmap=cmap,norm=norm)
else:
pcparams=dict(cmap=cmap)
if latlon: pcparams['latlon']=latlon
#############plot######################
pc=ax.pcolormesh(xs,ys,fld,**pcparams)
return pc
############################################################################
def add_cb(ax,pc,
units=None,
x0scale=1.,y0scale=1.,lscale=1.,labelsize=10,
manticks=None,manlabels=None,
orientation='vertical',
spacing='proportional'):
"""Adds a cbar to a plot in its own axis
Parameters:
----------
ax : [axis]
Subplot axis
pc :
pcolormesh or contourf handle
*x0scale*: [*1.*, float]
x0 scaling factor
*y0scale*: [*1.*, float]
y0 scaling factor
*lscale*: [*1.*, float]
length scaling factor (height for vertical, width for horizontal colorbars)
*labelsize*: [*10.*, float]
height scaling factor
*manticks*:[None]
list of colorbar ticks
*manlabels*:[None]
list of colorbar labels
*orientation*:[*'vertical'*,string]
orientation of colorbar
*spacing*:[*'proportional'*,string]
spacing of colorbar
Returns:
-----------
Nothing
"""
#make axis
box = ax.get_position()
fig = ax.get_figure()
if orientation=='vertical':
cbar_ax=fig.add_axes([box.x0+box.width*1.035*x0scale, box.y0*y0scale, 0.02, box.height*lscale])
if orientation=='horizontal':
cbar_ax=fig.add_axes([box.x0+box.width*(0.08+x0scale-1), box.y0+box.height*0.08*y0scale, box.width*lscale, 0.015])
#plot cbar
cbar=fig.colorbar(pc, cax=cbar_ax,extendfrac='auto',orientation=orientation,spacing=spacing)
cbar.ax.tick_params(labelsize=labelsize)
#units
if units is not None: cbar.set_label(units)
if manticks is not None:
cbar.set_ticks(manticks)
cbar.set_ticklabels(manticks)
if manlabels is not None:
cbar.set_ticklabels(manlabels)
############################################################################
#CONTOURPLOTS#################################################################
############################################################################
############################################################################
def add_co(ax,x,y,fld,
clevs=None,cint=None,cint0=None,coffset=0.,nclevspos=50,
color='darkgray',linewidth=1.5,
neg_dash='True',clevs_color=None):
"""add contour plot to axis.
Parameters:
-----------
ax : [axis]
Either the basemap (latlon) or figure axis (latpres)
x : [array]
A 1D array with x-dimensions (lon or lat)
y : [array]
A 1D array with y-dimensions (lat or plev)
fld : [array]
A 2D array with the data to be plotted
*clevs* : [ *None* | array or list]
A 1D array or list with clevs
*cint0* : [ *None* | float]
Contour interval value used to create clevs (centred around 0)
*cint* : [ *None* | float]
Contour interval value used to create clevs that (includes 0)
*coffset* : [ *0* | float]
Offset for creating clevs from cint
*nclevspos* : [ *50* | int]
Number of positive contour levels, used to Contour interval value
used to create clevs that include 0
*color* : [ *'darkgray'* | string ]
Color of contours
*linewidth*: [ *1.5* | int]
Linewidth of the contours
*neg_dash*: [ *True* | boolean ]
If true negative contours are dashed
*clevs_color*: [ *None* | list]
If specified, it will add up to 3 colorcontours (green,blue,red)
Returns:
--------
Nothing
"""
##### Determine if latlon, and make grid
if np.max(x)>90 and np.max(y)<359: #X is lon (not lat), Y is lat (not pres)
latlon=True
# Add cyclic lon if needed
if np.mod(x.shape,2) == 0:
fld,x = mpltk.basemap.addcyclic(fld,x)
if np.max(y)<90:
fld,y =add_poles(fld,y)
else:
latlon=False
xs,ys=np.meshgrid(x,y)
coparams=dict(latlon=latlon)
#############clevs######################################
if clevs is not None: clevs=np.array(clevs) #convert to array if it was a list
if cint0 is not None: #create clevs centred around 0
crange=(nclevspos-0.5)*cint0;
cmin=-crange; cmax=crange
clevs=np.arange(cmin,cmax+cint0,cint0)+coffset;
if cint is not None: #create clevs that includes 0
crange=nclevspos*cint;
cmin=-crange; cmax=crange
clevs=np.arange(cmin,cmax+cint,cint)+coffset;
#############contour settingss###############################
coparams['colors']=color
coparams['linewidths']=linewidth
#############Plot###############################
if clevs is None:
ax.contour(xs,ys,fld,**coparams)
else:
if np.max(clevs)>0:
coparams['levels']=clevs[clevs>0.]
ax.contour(xs,ys,fld,**coparams)
if np.min(clevs)<0:
coparams['levels']=clevs[clevs<0.]
CS_neg=ax.contour(xs,ys,fld,**coparams)
for c in CS_neg.collections:
if neg_dash:
c.set_dashes([(0, (3.0, 2.0))])
else:
c.set_dashes((None,None))
if 0. in clevs:
coparams['levels']=[0]
coparams['linewidths']=linewidth*2
ax.contour(xs,ys,fld,**coparams)
#additional contours
if clevs_color is not None:
if len(clevs_color)>=1:
ax.contour(xs,ys,fld,levels=[clevs_color[0]],colors='g',linewidths=1,latlon=latlon)
if len(clevs_color)>=2:
ax.contour(xs,ys,fld,levels=[clevs_color[1]],colors='b',linewidths=1,latlon=latlon)
if len(clevs_color)>=3:
ax.contour(xs,ys,fld,levels=[clevs_color[2]],colors='r',linewidths=1,latlon=latlon)
############################################################################
#SCATTERPLOTS#################################################################
############################################################################
############################################################################
def add_sc(ax,x,y,fld):
"""add scatter plot to axis.
Parameters:
-----------
ax : [axis]
Either the basemap (latlon) or figure axis (latpres)
x : [array]
A 1D array with x-dimensions (lon or lat)
y : [array]
A 1D array with y-dimensions (lat or plev)
fld : [array]
A 2D array with the data to be plotted
"""
##### Determine if latlon, and make grid
if np.max(x)>90 and np.max(y)<359: #X is lon (not lat), Y is lat (not pres)
latlon=True
# Add cyclic lon if needed
if np.mod(x.shape,2) == 0:
fld,x = mpltk.basemap.addcyclic(fld,x)
if np.max(y)<90:
fld,y =add_poles(fld,y)
else:
latlon=False
xs,ys=np.meshgrid(x,y)
print latlon
ax.scatter(xs,ys,s=fld)
############################################################################
def add_sc2d(ax,x,y):
"""2d scatterplot.
Parameters:
-----------
ax : [axis]
Either the basemap (latlon) or figure axis (latpres)
x : [array]
A 1D array with x-data
y : [array]
A 1D array with y-data
"""
ax.scatter(x,y)
############################################################################
#UTILS#######################################################################
############################################################################
def add_poles(fld,lat):
nlat=np.shape(fld)[0];
nlon=np.shape(fld)[1];
lat_new=np.zeros(nlat+2)
fld_new=np.ma.zeros((nlat+2,nlon))
if(lat[1]>lat[0]):
lat_new[0]=-90
lat_new[1:-1]=lat
lat_new[-1]=90
fld_new[0,:]=np.mean(fld[0,:])
fld_new[1:-1,:]=fld
for ilon in range(nlon): fld_new[-1,ilon]=np.ma.masked
return fld_new,lat_new
##save_fig##########################################################################
def mysavefig(fig,fnamesave):
fig.savefig(fnamesave,dpi=400,bbox_inches='tight')
##make_colors##########################################################################
def make_colors(cmap_name,cmapi=None):
"""Make array of colors rgb values
Returns:
-----------
Colors: array
Array of rgb values of colors
Notes:
-----------
Only to be used in rms_plots.py
"""
cmap=plt.get_cmap(cmap_name)
if cmapi is None:
cmapi=np.arange(cmap.N)
colors=cmap(np.asarray(cmapi))
#return
return colors
##qplot##########################################################################
def qplot(x,y,fld,
fnamesave=None):
"""Quick plot
Parameters:
-----------
x : [array]
A 1D array with x-dimensions (lon or lat)
y : [array]
A 1D array with y-dimensions (lat or plev)
fld : [array]
A 2D array with the data to be plotted
*fnamesave* [ *None* | string]
If given save the plot into the file fnamesave
Returns:
-----------
Figure handle
"""
#creat figure and axis
fig=plt.figure()
ax=plt.gca()
#determine latlon
##### Determine if latlon, and make grid
if np.max(x)>90 and np.max(y)<359: #X is lon (not lat), Y is lat (not pres)
latlon=True
else:
latlon=False
#create map and plot
if latlon:
bm=make_bm(ax=ax)