-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathJupyter_Notebooks.html
1522 lines (1223 loc) · 146 KB
/
Jupyter_Notebooks.html
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
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Jupyter Notebooks — Python Like You Mean It 0.12.0 documentation</title>
<link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />
<link rel="stylesheet" href="../_static/my_theme.css" type="text/css" />
<link rel="index" title="Index"
href="../genindex.html"/>
<link rel="search" title="Search" href="../search.html"/>
<link rel="top" title="Python Like You Mean It 0.12.0 documentation" href="../index.html"/>
<link rel="up" title="Module 1: Getting Started with Python" href="../module_1.html"/>
<link rel="next" title="Setting Up a Development Environment" href="Getting_Started_With_IDEs_and_Notebooks.html"/>
<link rel="prev" title="An Informal Introduction to Python" href="Informal_Intro_Python.html"/>
<script src="../_static/js/modernizr.min.js"></script>
</head>
<body class="wy-body-for-nav" role="document">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search">
<a href="../index.html" class="icon icon-home"> Python Like You Mean It
</a>
<div class="version">
0.12.0
</div>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<p class="caption"><span class="caption-text">Table of Contents:</span></p>
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="../intro.html">Python Like You Mean It</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="../module_1.html">Module 1: Getting Started with Python</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="SiteFormatting.html">A Quick Guide to Formatting</a></li>
<li class="toctree-l2"><a class="reference internal" href="GettingStartedWithPython.html">Introducing the Python Programming Language</a></li>
<li class="toctree-l2"><a class="reference internal" href="Installing_Python.html">Installing Python</a></li>
<li class="toctree-l2"><a class="reference internal" href="Informal_Intro_Python.html">An Informal Introduction to Python</a></li>
<li class="toctree-l2 current"><a class="current reference internal" href="#">Jupyter Notebooks</a><ul>
<li class="toctree-l3"><a class="reference internal" href="#Running-a-Notebook-Server-&-Creating-a-Notebook">Running a Notebook Server & Creating a Notebook</a></li>
<li class="toctree-l3"><a class="reference internal" href="#Notebook-Cells">Notebook Cells</a></li>
<li class="toctree-l3"><a class="reference internal" href="#An-Example-Notebook">An Example Notebook</a></li>
<li class="toctree-l3"><a class="reference internal" href="#Familiarizing-Yourself-with-Jupyter-Notebooks">Familiarizing Yourself with Jupyter Notebooks</a><ul>
<li class="toctree-l4"><a class="reference internal" href="#Markdown-Cells">Markdown Cells</a></li>
<li class="toctree-l4"><a class="reference internal" href="#Using-Jupyter-Notebooks-with-Other-Languages">Using Jupyter Notebooks with Other Languages</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="Getting_Started_With_IDEs_and_Notebooks.html">Setting Up a Development Environment</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../module_2.html">Module 2: The Essentials of Python</a></li>
<li class="toctree-l1"><a class="reference internal" href="../module_3.html">Module 3: The Essentials of NumPy</a></li>
<li class="toctree-l1"><a class="reference internal" href="../module_4.html">Module 4: Object Oriented Programming</a></li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
<nav class="wy-nav-top" role="navigation" aria-label="top navigation">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="../index.html">Python Like You Mean It</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="../index.html">Docs</a> »</li>
<li><a href="../module_1.html">Module 1: Getting Started with Python</a> »</li>
<li>Jupyter Notebooks</li>
<li class="wy-breadcrumbs-aside">
<a href="../_sources/Module1_GettingStartedWithPython/Jupyter_Notebooks.ipynb.txt" rel="nofollow"> View page source</a>
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<style>
/* CSS for nbsphinx extension */
/* remove conflicting styling from Sphinx themes */
div.nbinput,
div.nbinput div.prompt,
div.nbinput div.input_area,
div.nbinput div[class*=highlight],
div.nbinput div[class*=highlight] pre,
div.nboutput,
div.nbinput div.prompt,
div.nbinput div.output_area,
div.nboutput div[class*=highlight],
div.nboutput div[class*=highlight] pre {
background: none;
border: none;
padding: 0 0;
margin: 0;
box-shadow: none;
}
/* avoid gaps between output lines */
div.nboutput div[class*=highlight] pre {
line-height: normal;
}
/* input/output containers */
div.nbinput,
div.nboutput {
display: -webkit-flex;
display: flex;
align-items: flex-start;
margin: 0;
width: 100%;
}
@media (max-width: 540px) {
div.nbinput,
div.nboutput {
flex-direction: column;
}
}
/* input container */
div.nbinput {
padding-top: 5px;
}
/* last container */
div.nblast {
padding-bottom: 5px;
}
/* input prompt */
div.nbinput div.prompt pre {
color: #303F9F;
}
/* output prompt */
div.nboutput div.prompt pre {
color: #D84315;
}
/* all prompts */
div.nbinput div.prompt,
div.nboutput div.prompt {
min-width: 8ex;
padding-top: 0.4em;
padding-right: 0.4em;
text-align: right;
flex: 0;
}
@media (max-width: 540px) {
div.nbinput div.prompt,
div.nboutput div.prompt {
text-align: left;
padding: 0.4em;
}
div.nboutput div.prompt.empty {
padding: 0;
}
}
/* disable scrollbars on prompts */
div.nbinput div.prompt pre,
div.nboutput div.prompt pre {
overflow: hidden;
}
/* input/output area */
div.nbinput div.input_area,
div.nboutput div.output_area {
padding: 0.4em;
-webkit-flex: 1;
flex: 1;
overflow: auto;
}
@media (max-width: 540px) {
div.nbinput div.input_area,
div.nboutput div.output_area {
width: 100%;
}
}
/* input area */
div.nbinput div.input_area {
border: 1px solid #cfcfcf;
border-radius: 2px;
background: #f7f7f7;
}
/* override MathJax center alignment in output cells */
div.nboutput div[class*=MathJax] {
text-align: left !important;
}
/* override sphinx.ext.pngmath center alignment in output cells */
div.nboutput div.math p {
text-align: left;
}
/* standard error */
div.nboutput div.output_area.stderr {
background: #fdd;
}
/* ANSI colors */
.ansi-black-fg { color: #3E424D; }
.ansi-black-bg { background-color: #3E424D; }
.ansi-black-intense-fg { color: #282C36; }
.ansi-black-intense-bg { background-color: #282C36; }
.ansi-red-fg { color: #E75C58; }
.ansi-red-bg { background-color: #E75C58; }
.ansi-red-intense-fg { color: #B22B31; }
.ansi-red-intense-bg { background-color: #B22B31; }
.ansi-green-fg { color: #00A250; }
.ansi-green-bg { background-color: #00A250; }
.ansi-green-intense-fg { color: #007427; }
.ansi-green-intense-bg { background-color: #007427; }
.ansi-yellow-fg { color: #DDB62B; }
.ansi-yellow-bg { background-color: #DDB62B; }
.ansi-yellow-intense-fg { color: #B27D12; }
.ansi-yellow-intense-bg { background-color: #B27D12; }
.ansi-blue-fg { color: #208FFB; }
.ansi-blue-bg { background-color: #208FFB; }
.ansi-blue-intense-fg { color: #0065CA; }
.ansi-blue-intense-bg { background-color: #0065CA; }
.ansi-magenta-fg { color: #D160C4; }
.ansi-magenta-bg { background-color: #D160C4; }
.ansi-magenta-intense-fg { color: #A03196; }
.ansi-magenta-intense-bg { background-color: #A03196; }
.ansi-cyan-fg { color: #60C6C8; }
.ansi-cyan-bg { background-color: #60C6C8; }
.ansi-cyan-intense-fg { color: #258F8F; }
.ansi-cyan-intense-bg { background-color: #258F8F; }
.ansi-white-fg { color: #C5C1B4; }
.ansi-white-bg { background-color: #C5C1B4; }
.ansi-white-intense-fg { color: #A1A6B2; }
.ansi-white-intense-bg { background-color: #A1A6B2; }
.ansi-default-inverse-fg { color: #FFFFFF; }
.ansi-default-inverse-bg { background-color: #000000; }
.ansi-bold { font-weight: bold; }
.ansi-underline { text-decoration: underline; }
/* CSS overrides for sphinx_rtd_theme */
/* 24px margin */
.nbinput.nblast,
.nboutput.nblast {
margin-bottom: 19px; /* padding has already 5px */
}
/* ... except between code cells! */
.nblast + .nbinput {
margin-top: -19px;
}
/* nice headers on first paragraph of info/warning boxes */
.admonition .first {
margin: -12px;
padding: 6px 12px;
margin-bottom: 12px;
color: #fff;
line-height: 1;
display: block;
}
.admonition.warning .first {
background: #f0b37e;
}
.admonition.note .first {
background: #6ab0de;
}
.admonition > p:before {
margin-right: 4px; /* make room for the exclamation icon */
}
</style>
<div class="section" id="Jupyter-Notebooks">
<h1>Jupyter Notebooks<a class="headerlink" href="#Jupyter-Notebooks" title="Permalink to this headline">¶</a></h1>
<p>In recent years, the Jupyter Notebook has become a massively popular
tool for doing research-oriented work in Python and other languages
alike. Its emergence marked a paradigm shift in the way data science is
conducted.</p>
<p>A Jupyter notebook is similar to the IPython console, but, instead of
only being able to work with a single line of code at a time, you can
easily edit and re-execute <em>any</em> code that had been written in a
notebook. Furthermore, you can save a notebook, and thus return to it
later. Additionally, a notebook provides many terrific features. For
instance, you can embed visualizations of data within a notebook, and
write blocks of nicely-formatted text (using the <a class="reference external" href="https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet">Markdown
syntax</a>),
for presenting and explaining the contents of the notebook.</p>
<p>In this way, the Jupyter Notebook stands out as an excellent tool for
many practical applications. You could work on a notebook while you are
working through sections of this website, for instance, testing out
snippets of code, and answering reading-comprehension questions as you
proceed through the text, and using markdown-headers to visually
separate different portions of the notebook. When I do research, I am
always creating Jupyter notebooks in which I write code that analyzes
data, I plot various results, presented in different ways, and I write
detailed markdown-text blocks to document my work. The end result is
something that I can share with my labmates, and easily revisit months
later without having to struggle to recall what I had done.</p>
<p>Enough gushing about Jupyter notebooks. Let’s start using them!</p>
<div class="section" id="Running-a-Notebook-Server-&-Creating-a-Notebook">
<h2>Running a Notebook Server & Creating a Notebook<a class="headerlink" href="#Running-a-Notebook-Server-&-Creating-a-Notebook" title="Permalink to this headline">¶</a></h2>
<p>In your terminal, navigate to a directory (a.k.a folder) that you are
okay creating files in. If you don’t know how to do this, Google it!</p>
<p>Once you are in the desired directory, execute in your terminal (type
the following, and then hit <code class="docutils literal"><span class="pre"><ENTER></span></code>): <code class="docutils literal"><span class="pre">jupyter</span> <span class="pre">notebook</span></code></p>
<p>You should see some text appear in your terminal:</p>
<div class="figure" id="id1">
<img alt="Starting a jupyter notebook server on your machine" src="../_images/jupyter_login.PNG" />
<p class="caption"><span class="caption-text">Starting a jupyter notebook server on your machine</span></p>
</div>
<p>This is a “notebook server” that is running on your machine - it
basically handles all of the communication between your browser and your
machine. A new window or tab should open in your web browser, which
looks like a file explorer.</p>
<div class="figure" id="id2">
<img alt="File explorer that opens in your browser" src="../_images/jp_files.PNG" />
<p class="caption"><span class="caption-text">File explorer that opens in your browser</span></p>
</div>
<p>You can use this to enter subdirectories and to open up any Jupyter
notebooks that you have saved. <em>You will need to use this file explorer
any time that you want to open up a Jupyter notebook, old or new.</em> In
the top-right corner of this window, click on the dropdown menu labeled
“New”, and select the option <code class="docutils literal"><span class="pre">Python</span> <span class="pre">3</span></code>.</p>
<p><img alt="image0" src="../_images/jp_dropdown.PNG" /></p>
<p>A new tab will open in your browser, revealing a “Jupyter notebook”
called <code class="docutils literal"><span class="pre">Untitled.ipynb</span></code> running a Python 3 kernel. Clicking
<code class="docutils literal"><span class="pre">File</span> <span class="pre">></span> <span class="pre">Rename</span></code> in the notebook will enable you to name your notebook.
<code class="docutils literal"><span class="pre">.ipynb</span></code> is the file-type suffix used for Jupyter notebooks (<code class="docutils literal"><span class="pre">ipynb</span></code>
stands for “IPython-notebook”, which is what these notebooks were called
prior to 2014). The commands that you run in this notebook are
interpreted and executed by Python in the essentially same way that they
would be in a IPython console.</p>
<div class="admonition warning">
<p class="first fa fa-exclamation-circle"><strong>Jupyter Notebooks Do Not Use the Internet</strong>:</p>
<p class="last">Although a Jupyter notebook opens in your browser, <em>everything is
happening locally on your machine</em>. You don’t need to be connected to
the internet to work on a Jupyter notebook! The notebook server that you
ran in your terminal is simply routing communication from your browser
to your local machine. For instance, it is sending code to your CPython
interpreter to be executed.</p>
</div>
</div>
<div class="section" id="Notebook-Cells">
<h2>Notebook Cells<a class="headerlink" href="#Notebook-Cells" title="Permalink to this headline">¶</a></h2>
<p>Whereas a Python console only allows you to work on one line of code at
a time, a notebook allows you to write code within “cells” and to
execute these chunks of code cell-by-cell. In the first cell, write the
lines of code:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="mi">3</span>
<span class="n">y</span> <span class="o">=</span> <span class="mi">4</span>
</pre></div>
</div>
<p>then press <code class="docutils literal"><span class="pre"><SHIFT>+<ENTER></span></code>. This will execute all of the code within
the given cell (in this instance, assigning the variables <code class="docutils literal"><span class="pre">x</span></code> and
<code class="docutils literal"><span class="pre">y</span></code> with the values 3 and 4, respectively) and then creates a new cell
below. In the next cell type the code:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">+</span> <span class="n">y</span>
</pre></div>
</div>
<p>and hit <code class="docutils literal"><span class="pre"><SHIFT>+<ENTER></span></code> to execute this code. The number 7 will
appear beneath the cell - this, of course, is the value that is returned
when <code class="docutils literal"><span class="pre">3</span> <span class="pre">+</span> <span class="pre">4</span></code> is evaluated:</p>
<div class="figure" id="id3">
<img alt="jupyter notebook example" src="../_images/jupyter_early.png" />
<p class="caption"><span class="caption-text">jupyter notebook example</span></p>
</div>
<p>Notice that the notebook “knows” about its variables across its cells.
This doesn’t just work from top to bottom - you can define <code class="docutils literal"><span class="pre">z</span> <span class="pre">=</span> <span class="pre">2</span></code> in
the third cell, and then execute code that references <code class="docutils literal"><span class="pre">z</span></code> in the first
cell. What really matters is the <em>order</em> in which the cells are
executed. Notice that <code class="docutils literal"><span class="pre">In[1]</span></code> denotes that the top cell with the first
input-cell executed in the notebook, and <code class="docutils literal"><span class="pre">In[2]</span></code> denotes the second
cell that was executed.</p>
<p>Formally, the cells within a given notebook share a common “namespace”:
any variable defined in a cell can be referenced or redefined in any
other cell within the notebook. On the other hand, separate notebooks
are completely independent from one another. You can be working on
multiple notebooks at once, and they will never “know” about one
another.</p>
<p>A major value of using a notebook is that you can rapidly edit these
cells (say, change <code class="docutils literal"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">3</span></code> to <code class="docutils literal"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">10</span></code>), and re-execute them to
nimbly tinker with whatever code you are developing. Although simple,
this is a hugely powerful environment for prototyping code.</p>
</div>
<div class="section" id="An-Example-Notebook">
<h2>An Example Notebook<a class="headerlink" href="#An-Example-Notebook" title="Permalink to this headline">¶</a></h2>
<p>To show off a more exciting use-case, let’s create a notebook that plots
some data for us. We’ll use matplotlib, a Python library that is used
for plotting data, and NumPy, the premiere library for doing numerical
work in Python. We will import these libraries for use in our code. Next
we’ll define some mathematical functions. And finally, we’ll plot these
functions evaluated on a large number of closely-spaced points on the
domain.</p>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [1]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="nn">plt</span>
<span class="c1"># this tells Jupyter to embed matplotlib plots in the notebook</span>
<span class="o">%</span><span class="k">matplotlib</span> notebook
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [2]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="k">def</span> <span class="nf">sinc</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="k">return</span> <span class="n">np</span><span class="o">.</span><span class="n">sin</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="o">/</span> <span class="n">x</span>
<span class="k">def</span> <span class="nf">d_sinc</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="s2">"derivative of sinc-function"</span>
<span class="k">return</span> <span class="n">np</span><span class="o">.</span><span class="n">cos</span><span class="p">(</span><span class="n">x</span><span class="p">)</span><span class="o">/</span><span class="n">x</span> <span class="o">-</span> <span class="n">np</span><span class="o">.</span><span class="n">sin</span><span class="p">(</span><span class="n">x</span><span class="p">)</span><span class="o">/</span><span class="n">x</span><span class="o">**</span><span class="mi">2</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [3]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="c1"># evaluate functions at 1000 points evenly spaced in [-15, 15]</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">linspace</span><span class="p">(</span><span class="o">-</span><span class="mi">15</span><span class="p">,</span> <span class="mi">15</span><span class="p">,</span> <span class="mi">1000</span><span class="p">)</span>
<span class="n">f</span> <span class="o">=</span> <span class="n">sinc</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="n">df</span> <span class="o">=</span> <span class="n">d_sinc</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [4]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="c1"># plot the sinc-function and its derivative</span>
<span class="n">fig</span><span class="p">,</span> <span class="n">ax</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">subplots</span><span class="p">()</span>
<span class="n">ax</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">f</span><span class="p">,</span> <span class="n">color</span><span class="o">=</span><span class="s2">"red"</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="sa">r</span><span class="s2">"$sinc(x)$"</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">df</span><span class="p">,</span> <span class="n">color</span><span class="o">=</span><span class="s2">"blue"</span><span class="p">,</span> <span class="n">ls</span><span class="o">=</span><span class="s2">"--"</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="sa">r</span><span class="s2">"$\frac{d(sinc(x))}</span><span class="si">{dx}</span><span class="s2">$"</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_title</span><span class="p">(</span><span class="s2">"Example Notebook Plot"</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_xlabel</span><span class="p">(</span><span class="sa">r</span><span class="s2">"$x$ [radians]"</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">grid</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">legend</span><span class="p">();</span>
</pre></div>
</div>
</div>
<div class="nboutput docutils container">
<div class="prompt empty docutils container">
</div>
<div class="output_area docutils container">
<div></div>
<script type="text/javascript">
var element = document.currentScript.previousSibling.previousSibling;
/* Put everything inside the global mpl namespace */
window.mpl = {};
mpl.get_websocket_type = function() {
if (typeof(WebSocket) !== 'undefined') {
return WebSocket;
} else if (typeof(MozWebSocket) !== 'undefined') {
return MozWebSocket;
} else {
alert('Your browser does not have WebSocket support.' +
'Please try Chrome, Safari or Firefox ≥ 6. ' +
'Firefox 4 and 5 are also supported but you ' +
'have to enable WebSockets in about:config.');
};
}
mpl.figure = function(figure_id, websocket, ondownload, parent_element) {
this.id = figure_id;
this.ws = websocket;
this.supports_binary = (this.ws.binaryType != undefined);
if (!this.supports_binary) {
var warnings = document.getElementById("mpl-warnings");
if (warnings) {
warnings.style.display = 'block';
warnings.textContent = (
"This browser does not support binary websocket messages. " +
"Performance may be slow.");
}
}
this.imageObj = new Image();
this.context = undefined;
this.message = undefined;
this.canvas = undefined;
this.rubberband_canvas = undefined;
this.rubberband_context = undefined;
this.format_dropdown = undefined;
this.image_mode = 'full';
this.root = $('<div/>');
this._root_extra_style(this.root)
this.root.attr('style', 'display: inline-block');
$(parent_element).append(this.root);
this._init_header(this);
this._init_canvas(this);
this._init_toolbar(this);
var fig = this;
this.waiting = false;
this.ws.onopen = function () {
fig.send_message("supports_binary", {value: fig.supports_binary});
fig.send_message("send_image_mode", {});
if (mpl.ratio != 1) {
fig.send_message("set_dpi_ratio", {'dpi_ratio': mpl.ratio});
}
fig.send_message("refresh", {});
}
this.imageObj.onload = function() {
if (fig.image_mode == 'full') {
// Full images could contain transparency (where diff images
// almost always do), so we need to clear the canvas so that
// there is no ghosting.
fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);
}
fig.context.drawImage(fig.imageObj, 0, 0);
};
this.imageObj.onunload = function() {
fig.ws.close();
}
this.ws.onmessage = this._make_on_message_function(this);
this.ondownload = ondownload;
}
mpl.figure.prototype._init_header = function() {
var titlebar = $(
'<div class="ui-dialog-titlebar ui-widget-header ui-corner-all ' +
'ui-helper-clearfix"/>');
var titletext = $(
'<div class="ui-dialog-title" style="width: 100%; ' +
'text-align: center; padding: 3px;"/>');
titlebar.append(titletext)
this.root.append(titlebar);
this.header = titletext[0];
}
mpl.figure.prototype._canvas_extra_style = function(canvas_div) {
}
mpl.figure.prototype._root_extra_style = function(canvas_div) {
}
mpl.figure.prototype._init_canvas = function() {
var fig = this;
var canvas_div = $('<div/>');
canvas_div.attr('style', 'position: relative; clear: both; outline: 0');
function canvas_keyboard_event(event) {
return fig.key_event(event, event['data']);
}
canvas_div.keydown('key_press', canvas_keyboard_event);
canvas_div.keyup('key_release', canvas_keyboard_event);
this.canvas_div = canvas_div
this._canvas_extra_style(canvas_div)
this.root.append(canvas_div);
var canvas = $('<canvas/>');
canvas.addClass('mpl-canvas');
canvas.attr('style', "left: 0; top: 0; z-index: 0; outline: 0")
this.canvas = canvas[0];
this.context = canvas[0].getContext("2d");
var backingStore = this.context.backingStorePixelRatio ||
this.context.webkitBackingStorePixelRatio ||
this.context.mozBackingStorePixelRatio ||
this.context.msBackingStorePixelRatio ||
this.context.oBackingStorePixelRatio ||
this.context.backingStorePixelRatio || 1;
mpl.ratio = (window.devicePixelRatio || 1) / backingStore;
var rubberband = $('<canvas/>');
rubberband.attr('style', "position: absolute; left: 0; top: 0; z-index: 1;")
var pass_mouse_events = true;
canvas_div.resizable({
start: function(event, ui) {
pass_mouse_events = false;
},
resize: function(event, ui) {
fig.request_resize(ui.size.width, ui.size.height);
},
stop: function(event, ui) {
pass_mouse_events = true;
fig.request_resize(ui.size.width, ui.size.height);
},
});
function mouse_event_fn(event) {
if (pass_mouse_events)
return fig.mouse_event(event, event['data']);
}
rubberband.mousedown('button_press', mouse_event_fn);
rubberband.mouseup('button_release', mouse_event_fn);
// Throttle sequential mouse events to 1 every 20ms.
rubberband.mousemove('motion_notify', mouse_event_fn);
rubberband.mouseenter('figure_enter', mouse_event_fn);
rubberband.mouseleave('figure_leave', mouse_event_fn);
canvas_div.on("wheel", function (event) {
event = event.originalEvent;
event['data'] = 'scroll'
if (event.deltaY < 0) {
event.step = 1;
} else {
event.step = -1;
}
mouse_event_fn(event);
});
canvas_div.append(canvas);
canvas_div.append(rubberband);
this.rubberband = rubberband;
this.rubberband_canvas = rubberband[0];
this.rubberband_context = rubberband[0].getContext("2d");
this.rubberband_context.strokeStyle = "#000000";
this._resize_canvas = function(width, height) {
// Keep the size of the canvas, canvas container, and rubber band
// canvas in synch.
canvas_div.css('width', width)
canvas_div.css('height', height)
canvas.attr('width', width * mpl.ratio);
canvas.attr('height', height * mpl.ratio);
canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');
rubberband.attr('width', width);
rubberband.attr('height', height);
}
// Set the figure to an initial 600x600px, this will subsequently be updated
// upon first draw.
this._resize_canvas(600, 600);
// Disable right mouse context menu.
$(this.rubberband_canvas).bind("contextmenu",function(e){
return false;
});
function set_focus () {
canvas.focus();
canvas_div.focus();
}
window.setTimeout(set_focus, 100);
}
mpl.figure.prototype._init_toolbar = function() {
var fig = this;
var nav_element = $('<div/>')
nav_element.attr('style', 'width: 100%');
this.root.append(nav_element);
// Define a callback function for later on.
function toolbar_event(event) {
return fig.toolbar_button_onclick(event['data']);
}
function toolbar_mouse_event(event) {
return fig.toolbar_button_onmouseover(event['data']);
}
for(var toolbar_ind in mpl.toolbar_items) {
var name = mpl.toolbar_items[toolbar_ind][0];
var tooltip = mpl.toolbar_items[toolbar_ind][1];
var image = mpl.toolbar_items[toolbar_ind][2];
var method_name = mpl.toolbar_items[toolbar_ind][3];
if (!name) {
// put a spacer in here.
continue;
}
var button = $('<button/>');
button.addClass('ui-button ui-widget ui-state-default ui-corner-all ' +
'ui-button-icon-only');
button.attr('role', 'button');
button.attr('aria-disabled', 'false');
button.click(method_name, toolbar_event);
button.mouseover(tooltip, toolbar_mouse_event);
var icon_img = $('<span/>');
icon_img.addClass('ui-button-icon-primary ui-icon');
icon_img.addClass(image);
icon_img.addClass('ui-corner-all');
var tooltip_span = $('<span/>');
tooltip_span.addClass('ui-button-text');
tooltip_span.html(tooltip);
button.append(icon_img);
button.append(tooltip_span);
nav_element.append(button);
}
var fmt_picker_span = $('<span/>');
var fmt_picker = $('<select/>');
fmt_picker.addClass('mpl-toolbar-option ui-widget ui-widget-content');
fmt_picker_span.append(fmt_picker);
nav_element.append(fmt_picker_span);
this.format_dropdown = fmt_picker[0];
for (var ind in mpl.extensions) {
var fmt = mpl.extensions[ind];
var option = $(
'<option/>', {selected: fmt === mpl.default_extension}).html(fmt);
fmt_picker.append(option)
}
// Add hover states to the ui-buttons
$( ".ui-button" ).hover(
function() { $(this).addClass("ui-state-hover");},
function() { $(this).removeClass("ui-state-hover");}
);
var status_bar = $('<span class="mpl-message"/>');
nav_element.append(status_bar);
this.message = status_bar[0];
}
mpl.figure.prototype.request_resize = function(x_pixels, y_pixels) {
// Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,
// which will in turn request a refresh of the image.
this.send_message('resize', {'width': x_pixels, 'height': y_pixels});
}
mpl.figure.prototype.send_message = function(type, properties) {
properties['type'] = type;
properties['figure_id'] = this.id;
this.ws.send(JSON.stringify(properties));
}
mpl.figure.prototype.send_draw_message = function() {
if (!this.waiting) {
this.waiting = true;
this.ws.send(JSON.stringify({type: "draw", figure_id: this.id}));
}
}
mpl.figure.prototype.handle_save = function(fig, msg) {
var format_dropdown = fig.format_dropdown;
var format = format_dropdown.options[format_dropdown.selectedIndex].value;
fig.ondownload(fig, format);
}
mpl.figure.prototype.handle_resize = function(fig, msg) {
var size = msg['size'];
if (size[0] != fig.canvas.width || size[1] != fig.canvas.height) {
fig._resize_canvas(size[0], size[1]);
fig.send_message("refresh", {});
};
}
mpl.figure.prototype.handle_rubberband = function(fig, msg) {
var x0 = msg['x0'] / mpl.ratio;
var y0 = (fig.canvas.height - msg['y0']) / mpl.ratio;
var x1 = msg['x1'] / mpl.ratio;
var y1 = (fig.canvas.height - msg['y1']) / mpl.ratio;
x0 = Math.floor(x0) + 0.5;
y0 = Math.floor(y0) + 0.5;
x1 = Math.floor(x1) + 0.5;
y1 = Math.floor(y1) + 0.5;
var min_x = Math.min(x0, x1);
var min_y = Math.min(y0, y1);
var width = Math.abs(x1 - x0);
var height = Math.abs(y1 - y0);
fig.rubberband_context.clearRect(
0, 0, fig.canvas.width, fig.canvas.height);
fig.rubberband_context.strokeRect(min_x, min_y, width, height);
}
mpl.figure.prototype.handle_figure_label = function(fig, msg) {
// Updates the figure title.
fig.header.textContent = msg['label'];
}
mpl.figure.prototype.handle_cursor = function(fig, msg) {
var cursor = msg['cursor'];
switch(cursor)
{
case 0:
cursor = 'pointer';
break;
case 1:
cursor = 'default';
break;
case 2:
cursor = 'crosshair';
break;
case 3:
cursor = 'move';
break;
}
fig.rubberband_canvas.style.cursor = cursor;
}
mpl.figure.prototype.handle_message = function(fig, msg) {
fig.message.textContent = msg['message'];
}
mpl.figure.prototype.handle_draw = function(fig, msg) {
// Request the server to send over a new figure.
fig.send_draw_message();
}
mpl.figure.prototype.handle_image_mode = function(fig, msg) {
fig.image_mode = msg['mode'];
}
mpl.figure.prototype.updated_canvas_event = function() {
// Called whenever the canvas gets updated.
this.send_message("ack", {});
}
// A function to construct a web socket function for onmessage handling.
// Called in the figure constructor.
mpl.figure.prototype._make_on_message_function = function(fig) {
return function socket_on_message(evt) {
if (evt.data instanceof Blob) {
/* FIXME: We get "Resource interpreted as Image but
* transferred with MIME type text/plain:" errors on
* Chrome. But how to set the MIME type? It doesn't seem
* to be part of the websocket stream */
evt.data.type = "image/png";
/* Free the memory for the previous frames */
if (fig.imageObj.src) {
(window.URL || window.webkitURL).revokeObjectURL(
fig.imageObj.src);
}
fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(
evt.data);
fig.updated_canvas_event();
fig.waiting = false;
return;
}
else if (typeof evt.data === 'string' && evt.data.slice(0, 21) == "data:image/png;base64") {
fig.imageObj.src = evt.data;
fig.updated_canvas_event();
fig.waiting = false;
return;
}
var msg = JSON.parse(evt.data);