forked from guziy/CMOS-python-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmos2014-python-tutorial.py
1588 lines (1155 loc) · 33.5 KB
/
cmos2014-python-tutorial.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
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
#Necessary imports
import os
from netCDF4 import Dataset
# <markdowncell>
# Data handling and visualization using Python
# =============================================
#
#
# <span id="authors">
# Oleksandr (Sasha) Huziy, Johnathan Doyle, Martin Deshaies-Jacques
# <span>
#
# CMOS, June 2014
#
# <table class="logo">
# <tr><td>
# <img src="files/images/logo_2.png"/> <img src="files/images/crsng.png"/> <img src="files/images/logo_uqam_0.png"/>
# </td></tr>
# </table>
# <markdowncell>
# Outline part I
# ========
#
# * **Python basics**
#
# * Builtin data types
#
# * Operations on file system, strings and dates
#
# * Modules, classes and functions
#
#
# * **Libraries for scientific computing**
#
# * NumPy/SciPy
#
#
#
# * **Handling NetCDF4 files**
#
# * Netcdf4-python
# <markdowncell>
# Introduction and history
# =====
#
# ### Python is an interpreted, strictly typed programming language developed by *Guido Van Rossum*.
#
#
# ### It was created in 90s of the previous century and has seen 3 major releases from that time.
#
# ### There many implementations of Python (in C, Java, Python, ...), CPython implementation is used most widely and we are going to use it during the tutorial.
#
# ### Talk on Python history by Guido Van Rossum [here](http://www.youtube.com/watch?v=ugqu10JV7dk).
#
#
#
# <markdowncell>
# Syntax
# =======
# <codecell>
#Variable decalaration <-This is a comment
a = 10; b = "mama"; x = None;
x = [1,2,4, 5, "I am a fifth element"]
#looping
for el in x:
#Checking conditions
if isinstance(el, int):
print(el ** 2 % 10),
else:
msg = ", but my index is {0}."
msg = msg.format(x.index(el))
print(el + msg),
#now we are outside of the loop since no identation
print "\nSomething ..."
# <markdowncell>
# Syntax
# =======
# <codecell>
#accessing elements of a list
x[3], x[-1], x[1:-1]
# <markdowncell>
# ##Defining functions
# <codecell>
def myfirst_func(x, name = "Sasha"):
"""
This is the comment describing method
arguments and what it actually does
x - dummy argument that demonstrates
use of positional arguments
name - demonstrates use of keyword arguments
"""
print "Hello {0} !!!".format(name)
return 2, None, x
# <markdowncell>
# ##Calling functions
# <codecell>
#Calling the function f
myfirst_func("anything", name = "Oleks")
# <markdowncell>
# Python basics - code hierarchy
# ==============
#
# + Each python file is a python module, it can contain function and class definitions
#
#
# + A folder with python files and a file ```__init__.py``` (might be empty file) is called package
#
# <markdowncell>
# Exercises on basic syntax
# =====
#
# * Create a script `hello.py` in your favourite editor and add `print "Hello world"`, save and run it: `python hello.py`
#
#
# * Modify the script making it print squares of odd numbers from 13 to 61 inclusively.
#
#
# * What will this code print to console:
#
#
# <pre class="co">
# x = 1 #define a global variable
# def my_function(argument = x):
# print argument ** 2
# #change the value of the global variable
# x = 5
# my_function() #call the function defined above
# </pre>
# <codecell>
x = 1 #define a global variable
def my_function(argument = x):
print argument ** 2
#change the value of the global variable
x = 5
my_function() #call the function defined above
# <markdowncell>
# Builtin data containers
# =============
# ##Python provides the following data structures. Which are actually classes with attributes and methods.
#
# * `list` (range, *, +, pop, len, accessing list elements, slices, last element, 5 last elements)
#
#
# * `tuple` (not mutable, methods)
#
#
# * `dict` (accessing elements, keys, size)
#
#
# * `set` (set theoretical operations, cannot have 2 equal elements)
#
# <headingcell level=1>
# Builtin data containers (lists)
# <codecell>
#lists (you can conactenate and sort in place)
the_list = [1,2,3,4,5]; other_list = 5 * [6];
print the_list + other_list
# <codecell>
#Test if a number is inside a list
print 19 in the_list, 5 in the_list, (6 in the_list and 6 in other_list)
# <headingcell level=1>
# Builtin data containers (lists)
# <codecell>
#square eleaments of a list
#list comprehension
print [the_el ** 2 for the_el in the_list]
# <codecell>
#Generating list or iterable of integers
print range(1,20)
# <headingcell level=1>
# Builtin data containers (lists)
# <codecell>
##There are some utility functions that can be applied to lists
print sum(the_list), \
reduce(lambda x, y: x + y, the_list)
# <codecell>
#loop through several lists at the same time
for el1, el2 in zip(the_list, other_list):
print(el1+el2),
# <markdowncell>
# Builtin data containers (tuples)
# ======
# <codecell>
the_tuple = (1,2,3) #tuple is an immutable list, is hashable
print the_tuple[-1]
# <markdowncell>
# Builtin data containers (tuples)
# ======
# <codecell>
#tuples are immutable, e.g:
try:
the_tuple[1] = 25
except TypeError, te:
print te
# <markdowncell>
# Builtin data containers (dictionary)
# =====
# <codecell>
#dictionary
author_to_books = {
"Stephen King":
["Carrie","On writing","Green Mile"],
"Richard Feynman":
["Lectures on computation",
"The pleasure of finding things out"]
}
#add elements to a dictionary
author_to_books["Andrey Kolmogorov"] = \
["Foundations Of The Theory Of Prob..."]
# <markdowncell>
# Builtin data containers (dictionary)
# =====
# <codecell>
#print the list of authors
print author_to_books.keys()
# <codecell>
#Iterate over keys and values
for author, book_list in author_to_books.iteritems():
suffix = "s" if len(book_list) > 1 else ""
print("{0} book{1} by {2};\n".format(len(book_list), suffix, author)),
# <markdowncell>
# Exercises: builtin containers
# ======
# <markdowncell>
# * Find a sum of squares of all odd integers that are smaller than 100 in one line of code (Hint: use list comprehensions)
#
#
# * Find out what does `enumerate` do.
#
#
# * Implement recursive fibonacci function with caching, which given the index of a fibonacci number returns its value.
# <markdowncell>
# Modules and classes to operate on
# ==============
#
#
# * File system (```os, shutil, sys```)
#
# * create folder, list folder contents, check if file or folder exists
#
#
# * Strings (+, *, join, split, regular expressions)
#
#
# * Dates (datetime, timedelta, )
# <markdowncell>
# #File system
# <codecell>
import os
#print current directory
print os.getcwd()
# <markdowncell>
# #File system
# <codecell>
#get list of files in the current directory
flist = os.listdir(".")
print flist[:7]
# <markdowncell>
# #File system
# <codecell>
#Check if file exists
fname = flist[0]
print fname,":", os.path.isfile(fname), \
os.path.isdir(fname), \
os.path.islink(fname)
# <markdowncell>
# You might also find useful the following modules: `sys, shutil, path`
# <markdowncell>
# #Strings
# <codecell>
s = "mama"
#reverse (also works for lists)
print s[-1::-1]
# <codecell>
#Dynamically changing parts of a string
tpl = "My name is {0}. I am doing my {1}.\nI am {2} old.\nWeight is {3:.3f} kg"
print tpl.format("Black", "PhD", 25, 80.7823)
# <markdowncell>
# #Strings
# <codecell>
#Splitting
s = "This,is,a,sentence"
s_list = s.split(",")
print s_list
# <codecell>
#joining a list of strings
list_of_fruits = ["apple", "banana", "cherry"]
print "I would like to eat {0}.".format(" or ".join(list_of_fruits))
# <markdowncell>
# #Strings: regular expressions
# <codecell>
#regular expressions module
import re
msg = "Find 192, numbers 278: and -7 and do smth w 89"
groups = re.findall(r"-?\d+", msg)
print groups
print [float(el) for el in groups] #convert strings to floats
# <codecell>
#regular expressions module
groups = re.findall(r"-?\d+/\d+|-?\d+\.\d+|-?\.?\d+|-?\d+\.?", "Find 192.28940, -2/3 numbers 278: and -7 and .005 w 89,fh.5 -354.")
print groups
# <markdowncell>
# # Dates
# <codecell>
#What time is it
from datetime import datetime, timedelta
d = datetime.now(); print d
# <codecell>
#hours and minutes
d.strftime("%H:%M"), d.strftime("%Hh%Mmin")
# <markdowncell>
# # Dates: How long is the workshop?
# <codecell>
start_date = datetime(2013, 12, 17, 9)
end_date = datetime(2013, 12, 18, 17)
print end_date - start_date
# <codecell>
#you can mutiply the interval by an integer
print (end_date - start_date) * 2
# <markdowncell>
# Exercises: Operations with strings, dates and file system
# ======
#
# * Get list of all items in the folders from your `LD_LIBRARY_PATH` environment variable
#
#
# * Write a function that finds all the numbers in a string using `re` module (Note: make sure real numbers are also accounted for. Optionally you can also account for the fractions like 2/3)
#
#
# * Calculate your age in weeks using `timedelta`
#
#
# * Figure out on which day of week you were born (see the `calendar` module), you can have fun by determining on which day of week you'll have your birthday in 2014.
# <markdowncell>
# NumPy
# ========
# The library for fast manipulations with big arrays that fit into memory.
# <codecell>
import numpy as np
#Creating a numpy array from list
np_arr = np.asarray([1,23,4, 3.5,6,7,86, 18.9])
print np_arr
# <markdowncell>
# NumPy
# ========
# <codecell>
#Reshape
np_arr.shape = (2,4)
print np_arr
# <codecell>
#sum along a specified dimension, here
print np_arr.sum(axis = 1)
# <markdowncell>
# Numpy
# =====
# <codecell>
#create prefilled arrays
the_zeros = np.zeros((3,9))
the_ones = np.ones((3,9))
print the_zeros
print 20 * "-"
print the_ones
# <markdowncell>
# Numpy provides many vectorized functions to efficiently operate on arrays
# =====
# <codecell>
print np.sin(np_arr)
# <codecell>
print np.cross([1,0,0], [0,1,0])
# <markdowncell>
# Numpy: fancy indexing
# =====
# <codecell>
arr = np.random.randn(3,5)
print "Sum of positive numbers: ", arr[arr > 0].sum()
print "Sum over (-0.1 <= arr <= 0.1): ", \
arr[(arr >= -0.1) & (arr <= 0.1)].sum()
print "Sum over (-0.1 > arr) or (arr > 0.1): ", \
arr[(arr < -0.1) | (arr > 0.1)].sum()
# <markdowncell>
# Exercises: Numpy
# =====
#
# * Generate a 10 x 3 array of random numbers (in range \[0,1\]). For each row, pick the number closest to 0.5 ([source](http://scipy-lectures.github.io/intro/numpy/exercises.html#crude-integral-approximations)) *Hint:* use `np.argmin`.
#
#
# * Checkout numpy for MATLAB users transition [table](http://wiki.scipy.org/NumPy_for_Matlab_Users).
# <codecell>
arr = np.random.randn(10,3)
d = np.abs(arr - 0.5)
print arr
colinds = np.argmin(d, axis = 1)
rowinds = range(arr.shape[0])
arr[rowinds, colinds]
# <markdowncell>
# SciPy
# =======
#
# ## [Scipy lectures](http://scipy-lectures.github.io/)
# <markdowncell>
# SciPy packages
# =======
#
# It contains many paackages useful for data analysis
#
# |Package| Purpose|
# |:-------:|:----------:|
# | scipy.cluster | Vector quantization / Kmeans |
# | scipy.constants | Physical and mathematical constants |
# | scipy.fftpack | Fourier transform |
# | scipy.integrate| Integration routines |
# | scipy.interpolate| Interpolation |
# | scipy.io | Data input and output |
# | scipy.linalg| Linear algebra routines |
# | scipy.ndimage| n-dimensional image package |
# <markdowncell>
# SciPy packages (cont.)
# =======
#
# It contains many paackages useful for data analysis
#
# |Package| Purpose|
# |:-------:|:----------:|
# | scipy.odr | Orthogonal distance regression |
# | scipy.optimize | Optimization |
# | scipy.signal | Signal processing |
# | scipy.sparse | Sparse matrices |
# | scipy.spatial | Spatial data structures and algorithms |
# | scipy.special | Any special mathematical functions |
# | scipy.stats | Statistics |
# <markdowncell>
# SciPy: ttest example
# =======
# <codecell>
from scipy import stats
#generating random variable samples for different distributions
x1 = stats.norm.rvs(loc = 50, scale = 20, size=100)
x2 = stats.norm.rvs(loc=5, scale = 20, size=100)
print stats.ttest_ind(x1, x2)
x1 = stats.norm.rvs(loc = 50, scale = 20, size=100)
x2 = stats.norm.rvs(loc=45, scale = 20, size=100)
print stats.ttest_ind(x1, x2)
# <codecell>
font_size = 20
params = {
'xtick.labelsize': font_size,
'ytick.labelsize': font_size,
}
plt.rcParams.update(params) #set back font size to the default value
# <markdowncell>
# SciPy: integrate a function
# =====
# $$
# \int\limits_{-\infty}^{+\infty} e^{-x^2}dx \;=\; ?
# $$
# <codecell>
from scipy import integrate
# <codecell>
def the_func(x):
return np.exp(-x ** 2)
print integrate.quad(the_func, -np.Inf, np.inf)
# <codecell>
print "Exact Value sqrt(pi) = {0} ...".format(np.pi ** 0.5)
# <markdowncell>
# Exercises: SciPy
# =======
#
# * Calculate the integral over the cube D=\[0,1\] x \[0, 1\] x \[0,1\] ([source](http://scipy-lectures.github.io/intro/numpy/exercises.html)):
#
# $$
# \int\int\limits_{D}\int \left(x^y -z \right) dD
# $$
#
# *Hint: checkout* `scipy.integrate.tplquad`.
# <codecell>
def the_func_to_integr(x,y,z):
return x**y - z
integrate.tplquad(the_func_to_integr, 0,1, lambda x: 0, lambda x: 1, lambda x,y: 0, lambda x,y: 1)
# <markdowncell>
# Netcdf4-python
# =================
# ##The python module that for reading and writing NetCDF files in python, created by *Jeff Whitaker*.
# ##Requires installation of C libraries:
#
# * **NetCDF4**
#
#
# * **HDF5**
#
#
# <markdowncell>
# #Netcd4-python
#
# ## Below is the example of creating a netcdf file using the **netcdf4-python** library.
# <codecell>
from netCDF4 import Dataset
file_name = "test.nc"
if os.path.isfile(file_name):
os.remove(file_name)
#open the file for writing, you can Also specify format="NETCDF4_CLASSIC" or "NETCDF3_CLASSIC"
#The format is NETCDF4 by default
ds = Dataset(file_name, mode="w")
# <markdowncell>
# Netcdf4-python: create dimensions
# ==========
# <codecell>
ds.createDimension("x", 20)
ds.createDimension("y", 20)
ds.createDimension("time", None)
# <markdowncell>
# Netcdf4-python: create variables
# ==========
# <codecell>
var1 = ds.createVariable("field1", "f4", ("time", "x", "y"))
var2 = ds.createVariable("field2", "f4", ("time", "x", "y"))
# <markdowncell>
# #Write actual data to the file
# <codecell>
#generate random data and tell to the program where it should go
data = np.random.randn(10, 20, 20)
var1[:] = data
var2[:] = 10 * data + 10
#actually write data to the disk
ds.close();
# <markdowncell>
# Netcdf4-python: reading a netcdf file
# ==============
#
# Open the netcdf file for reading:
# <codecell>
from netCDF4 import Dataset
ds = Dataset("test.nc")
# <markdowncell>
# Select variables of interest: no data loading happens at this point
# ======
# <codecell>
#what variables are in the file
print ds.variables.keys()
#now data is a netcdf4 Variable object, which contain only links to the data
data1_var = ds.variables["field1"]
data2_var = ds.variables["field2"]
#You can query dimensions and shapes of the variables
print data1_var.dimensions, data1_var.shape
# <markdowncell>
# Read data from the netcdf file for corresponding variables and time steps
# ==========
# <codecell>
#now we ask to really read the data into the memory
all_data = data1_var[:]
#print all_data.shape
data1 = data1_var[1,:,:]
data2 = data2_var[2,:,:]
print data1.shape, all_data.shape, all_data.mean(axis = 0).mean(axis = 0).mean(axis = 0)
# <markdowncell>
# Outline part II
# ========
#
# * **Plotting libraries**
#
# * Matplotlib
#
# * Basemap
#
#
# * **Grouping and subsetting temporal data with ```pandas```**
#
#
# * **Interpolation using ```cKDTree``` (```KDTree```) class**
#
#
# * **Speeding up your code**
# <markdowncell>
# Matplotlib
# ============
#
# ##The module for creating publication quality plots (mainly 2D), created by *John Hunter*.
#
# ##[Matplotlib gallery](http://matplotlib.org/gallery.html)
#
#
# An alternative is PyNGL - a wrapper around NCL developed at NCAR.
#
# <markdowncell>
# Matplotlib
# =====
# Example taken from the matplotlib library and modified.
#
# Read some timeseries into memory and import external dependencies:
# <codecell>
import matplotlib.pyplot as plt
from datetime import datetime
import matplotlib.cbook as cbook
from matplotlib.dates import strpdate2num
from matplotlib.dates import DateFormatter
from matplotlib.dates import DayLocator, MonthLocator
datafile = cbook.get_sample_data('msft.csv', asfileobj=False)
dates, closes = np.loadtxt(datafile, delimiter=',',
converters={0: strpdate2num('%d-%b-%y')},
skiprows=1, usecols=(0,2), unpack=True)
# <markdowncell>
# Plot timeseries
# ===================
# <codecell>
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(dates, closes, lw = 2);
# <markdowncell>
# Format the x-axis properly
# ====
# <codecell>
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(dates, closes, lw = 2)
ax.xaxis.set_major_formatter(DateFormatter("%b\n%Y"))
ax.xaxis.set_minor_locator(DayLocator())
ax.xaxis.set_major_locator(MonthLocator())
# <markdowncell>
# Modify the way the graph looks
# =====
# <codecell>
def modify_graph(ax):
ax.xaxis.set_major_formatter(DateFormatter("%b"))
ax.xaxis.set_minor_locator(DayLocator())
ax.xaxis.set_major_locator(MonthLocator())
ax.yaxis.set_major_locator(MaxNLocator(nbins=5))
ax.grid()
ax.set_ylim([25.5, 30]); ax.set_xlim([dates[-1], dates[0]]);
# <markdowncell>
# Modify the way the graph looks
# =====
# <codecell>
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(dates, closes, "gray", lw = 3)
modify_graph(ax)
# <markdowncell>
# Let us draw the data we just saved to the netcdf file.
# ====
#
# Do necessary imports and create configuration objects.
# <codecell>
import matplotlib.pyplot as plt
from matplotlib.colors import BoundaryNorm
from matplotlib import cm
levels = [-30,-10, -3,-1,0,1,3,10,30,40]
bn = BoundaryNorm(levels, len(levels) - 1)
cmap = cm.get_cmap("jet", len(levels) - 1);
# <markdowncell>
# Matplotlib: actual plotting
# ============
# <codecell>
font_size = 20
params = {
'xtick.labelsize': font_size,
'ytick.labelsize': font_size,
'figure.figsize' : (10, 3)
}
plt.rcParams.update(params) #set back font size to the default value
def apply_some_formatting(axes, im):
axes[1].set_yticks([]);
axes[2].set_aspect(20);
cax = axes[2];
cax.set_anchor("W")
cb = plt.colorbar(im2, cax = axes[2]);
# <codecell>
fig, axes = plt.subplots(nrows=1, ncols=3)
im1 = axes[0].contourf(data1.transpose(),
levels = levels,
norm = bn, cmap = cmap)
im2 = axes[1].contourf(data2.transpose(),
levels = levels,
norm = bn, cmap = cmap)
apply_some_formatting(axes, im2)
# <markdowncell>
# Execises: Matplotlib
# =============
#
# * Reproduce the panel plot given in the example. (Try different colormaps)
#
#
# * Plot a timeseries of daily random data. (Show only month names as Jan, Feb, .. along the x-axis, make sure they do not overlap)
# <markdowncell>
# Pandas
# ====
#
# * ## Initially designed to process and analyse long timeseries
#
#
# * ## Author: *Wes McKinney*
#
# * ## Home page: [pandas.pydata.org](http://pandas.pydata.org/)
# <markdowncell>
# Load the same timeseries as for matplotlib example
# ======
# <codecell>
import pandas as pd
datafile = cbook.get_sample_data('msft.csv', asfileobj=False)
df = pd.DataFrame.from_csv(datafile); df.head(3)
# <markdowncell>
# Select the closes column
# ======
# <codecell>
closes_col_sorted = df.Close.sort_index()
closes_col_sorted.plot(lw = 2);
# <markdowncell>
# Group by month and plot monthly means
# ======
# <codecell>
df_month_mean = df.groupby(by = lambda d: d.month).mean()
df_month_mean = df_month_mean.drop("Volume", axis = 1)
df_month_mean.plot(lw = 3);
plt.legend(loc = 2);
# <markdowncell>
# It is easy to resample and do a rolling mean
# ======
# <codecell>
resampled_closes = closes_col_sorted.resample("5D", how=np.mean)
ax = pd.rolling_mean(resampled_closes, 4)[3:].plot(lw = 2);
# <markdowncell>
# Customizing the graph produced by pandas
# ======
# <codecell>