-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmatplotlib.tex
1044 lines (844 loc) · 50.9 KB
/
matplotlib.tex
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
\chapter{Introducción a matplotlib\\ Introduction to matplotlib}
\chaptermark{Intro to matplotlib \textreferencemark \ Intro to matplotlib}
\epigraph{El punto geométrico es invisible. De modo que lo debemos definir como un ente abstracto. Si pensamos en él materialmente, el punto se asemeja a un cero.
Cero que, sin embargo, oculta diversas propiedades «humanas». Para nuestra percepción este cero —el punto geométrico—está ligado a la mayor concisión. Habla, sin duda, pero con la mayor reserva.}{Vasili Kandinski, Punto y línea sobre plano}
\begin{paracol}{2}
Visualizar los datos es fundamental para poder comprender y transmitir ideas e información en ciencias e ingeniería.
Python tiene numerosas funciones gráficas que para mostrar muchos tipos de gráficos. Una de las librerías para visualizar datos de uso más extendido es \href{https://matplotlib.org/stable/}{matplotlib} a la que dedicamos este capítulo.
\switchcolumn
Visualising data is essential for understanding and conveying ideas and information in science and engineering.
Python has numerous graphics functions for displaying many types of graphics. One of the most widely used data visualisation libraries is \href{https://matplotlib.org/stable/}{matplotlib} to which we dedicate this chapter.
\switchcolumn
Importaremos la biblioteca matplotlib de la siguiente manera
\switchcolumn
We can import matplotlib as follows:
\end{paracol}
\begin{minted}{python}
import matplotlib as mpl
\end{minted}
\begin{paracol}{2}
\paragraph{matplotlib.pyplot} es una colección de funciones que hacen que matplotlib funcione como MATLAB. Cada función de pyplot realiza algún cambio en una figura: por ejemplo, crea una figura, crea un área de trazado en una figura, traza algunas líneas en un área de trazado, decora el trazado con etiquetas, etc.
En matplotlib.pyplot la figura se conserva a través de las llamadas a funciones, de modo que las funciones de trazado se ejecutan sobre los ejes actuales.
\switchcolumn
\paragraph{matplotlib.pyplot} is a collection of functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: for example, it creates a figure, creates a plot area in a figure, draws some lines in a plot area, decorates the plot with labels, etc.
In matplotlib.pyplot the figure is preserved across function calls, so that the plotting functions are executed on the current axes.
\switchcolumn
Para crear gráficas usando Matplotlib necesitaremos una figura. Cada figura tiene un par (o más) de ejes y un área que es donde se dibujarán los puntos en el sistema de coordenadas que decidamos. Además podremos poner títulos, leyendas etc...
\switchcolumn
To create graphs using Matplotlib we will need a figure. Each figure has a pair (or more) of axes and an area which is where the points will be drawn in the coordinate system of your choice. In addition we can put titles, legends etc...
\switchcolumn
La manera más sencilla de crear una figura es empleando el método \texttt{figure} que creará una figura en la que posteriormente podremos añadir ejes, títulos y más cosas. Simplemente llamando a \texttt{figure} creamos un objeto de tipo figura, aunque también podemos darle de manera opcional parámetros como el tamaño, el color de fondo y más.
\switchcolumn
The easiest way to create a figure is to use the \texttt{figure} method which will create a figure to which we can later add axes, titles and more. Simply by calling \texttt{figure} we create an object of type figure, although we can also optionally give it parameters such as size, background colour and more.
\end{paracol}
\begin{paracol}{2}
\end{paracol}
\begin{minted}{python}
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(2, 2), facecolor='lightskyblue',
layout='constrained')
fig =plt.figure
\end{minted}
\section{Dibujar en 2D}
\begin{paracol}{2}
Podemos dibujar facilmente usando matplotlib.pyplot es mediante el método \texttt{plot}. A este método le pasaremos dos vectores con las coordenadas $x$ e $y$ de los puntos que queremos representar (evidentemente tendremos que asegurarnos de que tienen la misma longitud).
Por ejemplo si generamos unos vectores de coordenadas como los siguientes
$$x=(0,2,-1,-2)$$
$$y=(0,3,2,-4)$$
y se los pasamos al método \texttt{plot} pyplot dibujará los puntos $(x,y)$ y los unirá con rectas, como puede verse en la figura \ref{fig:pyplot-simple}.
\switchcolumn
The easiest way to draw using matplotlib.pyplot is by using the \texttt{plot} method. To this method we will pass two vectors with the $x$ and $y$ coordinates of the points we want to represent (obviously we will have to make sure that they have the same length).
For example, if we generate coordinate vectors such as
$$x=(0,2,-1,-2)$$
$$y=(0,3,2,-4)$$
and pass them to the pyplot method, it will draw the points $(x,y)$ and join them with straight lines, as can be seen in the figure \ref{fig:pyplot-simple}.
\end{paracol}
\begin{minted}{python}
import numpy as np
import matplotlib.pyplot as plt
x=np.array([0, 2, -1, -2])
y=np.array([0, 3, 2, -4])
plt.figure
plt.plot(x,y)
\end{minted}
\begin{figure}[h]
\centering
\includegraphics[width=0.5\linewidth]{figuras/pyplot01.png}
\bicaption{Ejemplo sencillo de pyplot.} {Simple pyplot example.}
\label{fig:pyplot-simple}
\end{figure}
\begin{paracol}{2}
Además de las coordenadas de los puntos $(x,y)$ al método \texttt{pyplot.plot} podemos darle un tercer argumento indicando el formato (color y forma) con el que queremos que se grafiquen los puntos y opcionalmente la línea que los una.
Algunos de los colores y formatos admitidos están en las tablas \ref{tab:colores}, \ref{tab:puntos} y \ref{tab:lineas}. Para más información consulta la ayuda de \texttt{pyplot.plot}.
\begin{table}
\centering
\begin{tabular}{|c|c|} \hline
\textbf{Símbolo} & \textbf{Color}\\
b& azul \\ \hline
r& rojo \\ \hline
g& verde \\ \hline
m& magenta\\ \hline
c& cian\\ \hline
y& amarillo\\ \hline
k& negro\\ \hline
w& blanco\\ \hline
\end{tabular}
\caption{Colores de los puntos}
\label{tab:colores}
\end{table}
\begin{table}
\centering
\begin{tabular}{|c|c|} \hline
\textbf{Símbolo} & \textbf{Formato punto}\\
.& punto \\ \hline
,& píxel\\ \hline
o& círculo \\ \hline
s& cuadrado\\ \hline
$\wedge$ & triángulo hacia abajo\\ \hline
v& triángulo hacia arriba\\ \hline
p& pentágono\\ \hline
*& asterisco\\ \hline
\end{tabular}
\caption{Algunos de los marcadores de puntos}
\label{tab:puntos}
\end{table}
\begin{table}
\centering
\begin{tabular}{|c|c|} \hline
\textbf{Símbolo} & \textbf{Tipo de línea}\\
-& sólida \\ \hline
--& discontínua\\ \hline
-.& punto-raya \\ \hline
:& de puntos\\ \hline
\end{tabular}
\caption{Tipos de línea}
\label{tab:lineas}
\end{table}
\switchcolumn
In addition to the coordinates of the points $(x,y)$, we can give the \texttt{pyplot.plot} method a third argument indicating the format (colour and shape) in which we want the points to be plotted and optionally the line that joins them.
Some of the colours and formats supported are in the tables \ref{tab:colours}, \ref{tab:dots} and \ref{tab:lines}. For more information, see the help for \texttt{pyplot.plot}.
\begin{table}
\centering
\begin{tabular}{|c|c|} \hline
\textbf{Symbol} & \textbf{Color}\\
b& blue \\ \hline
r& red \\ \hline
g& green \\ \hline
m& magenta\\ \hline
c& cyan\\ \hline
y& yellow\\ \hline
k& black\\ \hline
w& white\\ \hline
\end{tabular}
\caption{Point colors}
\label{tab:colours}
\end{table}
\begin{table}
\centering
\begin{tabular}{|c|c|} \hline
\textbf{Symbol} & \textbf{Point format}\\
.& point \\ \hline
,& pixel\\ \hline
o& circle \\ \hline
s& square\\ \hline
$\wedge$ & down triangle\\ \hline
v& up triangle\\ \hline
p& pentagon\\ \hline
*& star\\ \hline
\end{tabular}
\caption{Some point markers}
\label{tab:dots}
\end{table}
\begin{table}
\centering
\begin{tabular}{|c|c|} \hline
\textbf{Symbol} & \textbf{Line type}\\
-& solid \\ \hline
--& dashed\\ \hline
-.& dash and dot\\ \hline
:& dotted\\ \hline
\end{tabular}
\caption{Line types}
\label{tab:lines}
\end{table}
\switchcolumn
Se puede combinar un símbolo de cada tipo en un mismo \texttt{plot}. Así por ejemplo si queremos representar los datos anteriores unidos mediante una línea de puntos,
\begin{minted}{python}
plt.plot(x,y,':')
\end{minted}
Si queremos que pinte solo los puntos sin unirlos con líneas y en color rojo,
\begin{minted}{python}
plt.plot(x,y,'.r')
\end{minted}
Si queremos que pinte los puntos representados por triángulos con el vértice hacia arriba, unidos mediante una línea continua y en color negro,
\begin{minted}{python}
plt.plot(x,y,'-^k')
\end{minted}
\switchcolumn
It is possible to combine one symbol of each type in the same text. So for example if we want to represent the above data joined by a dotted line,
\begin{minted}{python}
plt.plot(x,y,':')
\end{minted}
If we want it to paint only the dots without joining them with lines and in red,
\begin{minted}{python}
plt.plot(x,y,'.r')
\end{minted}
If we want it to paint the points represented by triangles with the vertex upwards, joined by a continuous line and in black,
\begin{minted}{python}
plt.plot(x,y,'-^k')
\end{minted}
\switchcolumn
La figura \ref{fig:tplot} muestra los resultados de las combinaciones de símbolos que acabamos de describir.
\switchcolumn
Figure \ref{fig:tplot} shows the results of the symbol combinations just described.
\end{paracol}
\begin{figure}
\centering
\includegraphics[width=1\linewidth]{figuras/tipos_plot.png}
\bicaption{Ejemplos de dibujos con diferente formato}{Different uses of plot}
\label{fig:tplot}
\end{figure}
\begin{paracol}{2}
\paragraph{Scatter.} También podemos dibujar los puntos $x$, $y$, por separado sin unirlos usando el método \texttt{scatter(x,y)}.
\switchcolumn
\paragraph{Scatter.} We can also draw the points $x$, $y$, separately without joining them using the method \texttt{scatter(x,y)}.
\end{paracol}
\begin{paracol}{2}
\subsection{Trabajar con múltiples figuras}
Con \texttt{matplotlib.pyplot} se pueden dibujar diferentes gráficas en una misma figura usando el método \texttt{subplot}. Con este méotodo crearemos una figura donde las distintas gráficas estarán dispuestas a modo de tabla. A este método le indicaremos mediante parámetros de entrada el número de filas, el número de columnas y la posición donde se va a dibujar la siguiente gráfica.
En el siguiente ejemplo se crean dos gráficas dentro de la misma figura en dos filas y una columna. En la primera se dibuja la gráfica del coseno y en la segunda la del seno. El resultado puede verse en la figura \ref{fig:subplot_01}.
\begin{minted}{python}
import numpy as np
import matplotlib.pyplot as plt
t1 = np.arange(0.0, 5.0, 0.1)
plt.subplot(2,1,1)
plt.plot(t1,np.cos(t1),'r.-')
plt.subplot(2,1,2)
plt.plot(t1,np.sin(t1),'b.-')
\end{minted}
\switchcolumn
\subsection{Working with multiple figures}
With \texttt{matplotlib.pyplot} you can draw different graphs in the same figure using the \texttt{subplot} method. With this method we will create a figure where the different graphs will be arranged as a table. To this method we will indicate by means of input parameters the number of rows, the number of columns and the position where the next graph is going to be drawn.
In the following example, two graphs are created within the same figure in two rows and one column. In the first one the cosine graph is drawn and in the second one the sine graph is drawn. The result can be seen in figure \ref{fig:subplot_01}.
\begin{minted}{python}
import numpy as np
import matplotlib.pyplot as plt
t1 = np.arange(0.0, 5.0, 0.1)
plt.subplot(2,1,1)
plt.plot(t1,np.cos(t1),'r.-')
plt.subplot(2,1,2)
plt.plot(t1,np.sin(t1),'b.-')
\end{minted}
\end{paracol}
\begin{figure}
\centering
\includegraphics[width=0.75\linewidth]{figuras/subplot_01.png}
\bicaption{Dos gráficas en una misma figura usando \texttt{subplot}}{Two graphs in one figure using \texttt{subplot}}
\label{fig:subplot_01}
\end{figure}
\begin{paracol}{2}
Se puede añadir texto en cualquier parte del dibujo mediante el método \texttt{text} indicando las coordenadas donde se quiere poner el texto y el texto deseado. También se puede poner un texto como título de la figura, usando \texttt{title}, o etiquetando los ejes con \texttt{xlabel}, \texttt{ylabel}.
Por ejemplo el siguiente código da lugar a la figura \ref{fig:plot_text}.
\switchcolumn
Text can be added anywhere on the drawing using the \texttt{text} method, indicating the coordinates where the text is to be placed and the desired text. You can also put a text as the title of the figure, using \texttt{title}, or by labelling the axes with \texttt{xlabel}, \texttt{ylabel}.
For example, the following code results in the following figure \ref{fig:plot_text}.
\end{paracol}
\begin{minted}{python}
import numpy as np
import matplotlib.pyplot as plt
plt.figure()
t=np.arange(0.0,5,0.01)
y=np.exp(-t) * np.cos(2*np.pi*t)
plt.plot(t,y)
plt.title("Evolución de un sistema amortiguado")
plt.xlabel('t(s)')
plt.ylabel('x(m)')
plt.text(2.5,0.8,'$x=e^{-t}\cos(2\pi \cdot t)$')
\end{minted}
\begin{figure}
\centering
\includegraphics[width=0.75\linewidth]{figuras/plot_text.png}
\bicaption{Figura con texto en etiquetas}{Figure with text and labels}
\label{fig:plot_text}
\end{figure}
\begin{paracol}{2}
\subsection{Ejes no lineales}
\texttt{Matplotlib.pytplot} cuenta con un método para definir la escala de los ejes, son los métodos \texttt{xscale} e \texttt{yscale}. Estos métodos pueden recibir como argumento el tipo de escala del eje, a elegir entre los siguientes:
\begin{itemize}
\item \texttt{"linear"} para definir una escala lineal
\item \texttt{"log"} para definir una escala logarítmica de eje positivo
\item \texttt{"symlog"} para definir una escala logarítmica con tramo positivo y negativo centrado en el cero (como los valores del logaritmo en torno al cero tienden a infinito hay una zona en torno al cero donde considera la escala lineal)
\item \texttt{"logit"} escala logarítmica entre $0$ y $1$
\end{itemize}
Tanto \texttt{xscale} como \texttt{yscale} permiten definir la escala mediante una función que le definamos nosotros.
En el siguiente ejemplo de código puede verse un ejemplo de uso de los métodos \texttt{xscale} e \texttt{yscale} para generar la figura \ref{fig:scale}.
Como se ve en la figura \ref{fig:scale} las divisiones del eje logarítmico (eje y en la segunda figura y ambos en la tercera) aparecen marcadas como potencias de 10. Como estamos representando empleando el logaritmo decimal de la variable, las divisiones se corresponden con el exponente de la potencia de 10 de cada división, $\log_{10}(10^n)=n$.
En segundo lugar hemos empleado un nuevo método: \texttt{grid()}. Este método añade una retícula al gráfico de modo que sea más fácil ver los valores que toman las variables en cada punto de la gráfica. Si se invoca el método \texttt{grid()} sin parámetros cambia la retícula de visible a invisible y viceversa.
\switchcolumn
\subsection{Nonlinear axis}
\texttt{Matplotlib.pytplot} has a method to define the scale of the axes, these are the methods \texttt{xscale} and \texttt{yscale}. These methods can take as an argument the scale type of the axis, choose from the following:
\begin{itemize}
\item ‘linear’ to define a linear scale
\item \texttt{‘log’} to define a positive-axis logarithmic scale
\item \texttt{‘symlog’} to define a logarithmic scale with a positive and negative span centred at zero (as the values of the logarithm around zero tend to infinity there is a zone around zero where the linear scale is considered)
\item{‘logit’} logarithmic scale between $0$ and $1$.
\end{itemize}
Both \texttt{xscale} and \texttt{yscale} allow the scale to be defined by a function that we define.
The following code example shows an example of using the \texttt{xscale} and \texttt{yscale} methods to generate the \ref{fig:scale} figure.
As can be seen in the figure \ref{fig:scale} the divisions of the logarithmic axis (y-axis in the second figure and both in the third figure) are marked as powers of 10. As we are representing using the decimal logarithm of the variable, the divisions correspond to the exponent of the power of 10 of each division, $\log_{10}(10^n)=n$.
Secondly, we have employed a new method: \text{grid()}. This method adds a grid to the graph so that it is easier to see the values taken by the variables at each point on the graph. Calling the \texttt{grid()} method without parameters toggles the visibility of the grid.
\end{paracol}
\begin{minted}{python}
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(0,10,100)
y=np.exp(x)
plt.figure()
plt.subplot(3,1,1)
plt.plot(x,y)
plt.grid()
plt.xlabel("Escala lineal")
plt.ylabel("Escala lineal")
plt.title("$y=e^x$")
plt.subplot(3,1,2)
plt.plot(x,y)
plt.yscale('log')
plt.xlabel("Escala lineal")
plt.ylabel("Escala logarítmica")
plt.grid()
plt.subplot(3,1,3)
plt.plot(x,y)
plt.xscale('log')
plt.yscale('log')
plt.xlabel("Escala logarítmica")
plt.ylabel("Escala logarítmica")
plt.grid()
\end{minted}
\begin{figure}[h]
\centering
\includegraphics[width=1\linewidth]{figuras/plt_log_scales.png}
\bicaption{Gráfica de la función $y=e^x$ con ejes en escala lineal y logarítmica}{Graph of the function $y=e^x$ with axes on linear and logarithmic scale}
\label{fig:scale}
\end{figure}
\begin{paracol}{2}
\subsection{Gráfica en coordenadas polares}
Usando el método \texttt{polar} podemos representar funciones en coordenadas polares. El primer argumento es un ángulo en radianes y el segundo el correspondiente radio. La figura \ref{fig:sp} muestra la espiral,
\begin{equation*}
r=2\cdot\sqrt{\theta}
\end{equation*}
Para el intervalo angular $[0,8\pi]$.
\switchcolumn
\subsection{Polar coordinates graph}
Using the \texttt{polar} method we can plot functions in polar coordinates. The first argument is an angle in radians and the second the corresponding radius. The figure \ref{fig:sp} shows the spiral,
\begin{equation}
r=2\cdot\sqrt{\theta}
\end{equation}
For the angular interval $[0,8\pi]$.
\end{paracol}
\begin{minted}{python}
import numpy as np
import matplotlib.pyplot as plt
theta=np.linspace(0,8*np.pi,100)
radio=2*theta
plt.figure()
plt.polar(theta,radio,'b.-')
plt.grid(visible=True)
plt.title("Espiral en polares")
\end{minted}
\begin{figure}[h]
\centering
\includegraphics[width=0.75\linewidth]{figuras/plt_polar.png}
\bicaption{Espiral en coordenadas polares}{Spiral plot using polar coordinates}
\label{fig:sp}
\end{figure}
\begin{paracol}{2}
\subsection{Otras representaciones gráficas}
Con \texttt{matplotlib.pyplot} tenemos más opciones para hacer otro tipo de representaciones gráficas.
\paragraph{hist}. Este método permite dibujar el histograma de una colección de datos. El histograma representa cuántos datos de una colección caen dentro de un intervalo dado. El método \texttt{hist} necesita como parámetro de entrada un vector de datos. Si no se le indica otra cosa los datos se agrupan en $10$ intervalos. Si se quiere cambiar el número de intervalos se puede indicar con el parámetro \texttt{bin}. En el siguiente ejemplo se dibuja el histograma de los datos de coches por cada $1000$ habitantes usando el método \texttt{hist} con el número de intervalos por defecto, con $5$ intervalos y con $10$. Los datos se cargan de un fichero llamado \textit{coches.dat} y la figura \ref{fig:plt_hist} es la figura resultante.
\switchcolumn
\subsection{Other graphical representations}
With \texttt{matplotlib.pyplot} we have more options to make other types of graphical representations.
\paragraph{hist}. This method allows you to draw the histogram of a collection of data. The histogram represents how much data in a collection falls within a given interval. The \texttt{hist} method requires a vector of data as input parameter. Unless otherwise specified, the data is grouped into $10$ intervals. If you want to change the number of intervals you can specify it with the parameter \texttt{bin}. In the following example the histogram of the car data per $1000$ inhabitants is drawn using the \texttt{hist} method with the default number of intervals, with $5$ intervals and with $10$ intervals. The data is loaded from a file called \textit{cars.dat} and the resulting figure \ref{fig:plt_hist} is the resulting figure.
\end{paracol}
\begin{minted}{python}
import numpy as np
import matplotlib.pyplot as plt
# Abrir el archivo en modo lectura
with open('coches.dat', 'r') as file:
lineas=file.readlines()
f=len(lineas)
n=np.zeros([f])
i=0
for row in lineas:
n[i]=float(row)
i+=1
plt.figure()
plt.subplot(1,3,1)
plt.hist(n)
plt.grid(visible=True)
plt.title("10 intervalos")
plt.xlabel("Coches por cada 1000 habitantes")
plt.ylabel("Número de paises")
plt.subplot(1,3,2)
plt.hist(n, bins=5)
plt.grid(visible=True)
plt.title("5 intervalos")
plt.xlabel("Coches por cada 1000 habitantes")
plt.ylabel("Número de paises")
plt.subplot(1,3,3)
plt.hist(n,bins=20)
plt.grid(visible=True)
plt.title("20 intervalos")
plt.xlabel("Coches por cada 1000 habitantes")
plt.ylabel("Número de paises")
\end{minted}
\begin{figure}
\centering
\includegraphics[width=1\linewidth]{figuras/plt_hist.png}
\bicaption{Histogramas del número de automóviles por cada $1000$ habitantes}{}
\label{fig:plt_hist}
\end{figure}
\begin{paracol}{2}
\section{Dibujar en 3D}
En tres dimensiones es posible representar dos tipos de gráficos: puntos y curvas, análogos a los representados en dos dimensiones y además superficies en el espacio.
\paragraph{subplots} Este método encapsula todo lo necesario para crear una figura y un conjunto de subfiguras contenidas en ella. Podemos indicarle muchos parámetros como el número de filas y de columnas de la rejilla de subfiguras, si se comparten o no los ejes entre ellas etc. También podemos indicar, mediante un diccionario qué tipo de proyección queremos usar en los ejes creados. Concretamente mediante el par clave-valor siguiente estamos indicando que queremos ejes en 3d \textit{subplot\_kw="projection":"3d"}.
\switchcolumn
\section{3D plots}
In three dimensions it is possible to represent two types of graphics: points and curves, analogous to those represented in two dimensions, and also surfaces in space.
\paragraph{subplots} This method encapsulates everything needed to create a figure and a set of subfigures contained in it. We can indicate many parameters such as the number of rows and columns of the grid of subfigures, whether or not the axes are shared between them, etc. We can also indicate, by means of a dictionary, which type of projection we want to use in the axes created. Concretely, by means of the following key-value pair, we are indicating that we want 3d axes \textit{subplot\_kw=‘projection’: ‘3d’}.
\end{paracol}
\begin{minted}{python}
matplotlib.pyplot.subplots(nrows=1, ncols=1, *, sharex=False,
sharey=False, squeeze=True, width_ratios=None, height_ratios=None,
subplot_kw=None, gridspec_kw=None, **fig_kw)
\end{minted}
\begin{paracol}{2}
Por ejemplo, podemos representar la curva,
\begin{align*}
y&=\sin(2\pi x)\\
z&=\cos(2\pi x)
\end{align*}
Para ello, seleccionamos un intervalo de valores para $x \in (0,2)$, y calculamos los correspondientes valores de $y$ y $z$. Los representamos usando el método \textit{scatter}, figura \ref{fig:3dscatter}.
\switchcolumn
For example, we can represent the curve,
\begin{align*}
y&=\sin(2\pi x)\\
z&=\cos(2\pi x)
\end{align*}
To do this, we select an interval of values for $x \in (0,2)$, and calculate the corresponding values of $y$ and $z$. Then, we plot them using the \textit{scatter} method, Figure \ref{fig:3dscatter}.
\end{paracol}
\begin{minted}{python}
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(0,2,100)
y=np.sin(2*np.pi*x)
z=np.cos(2*np.pi*x)
fig,ax=plt.subplots(subplot_kw={"projection": "3d"})
ax.scatter(x,y,z)
\end{minted}
\begin{figure}
\centering
\includegraphics[width=0.5\linewidth]{figuras/scatter3d.png}
\bicaption{Representación en 3 dimensiones usando \textit{scatter}}{3D plot using \textit{scatter}}
\label{fig:3dscatter}
\end{figure}
\begin{paracol}{2}
\subsection{Superficies}
Para dibujar una superficie emplearemos el método \textit{plot\_surface}. Igual que en el caso del método \textit{scatter} tendremos que crear previamente una figura y unos ejes en 3 dimensiones usando \textit{subplots} e indicando que se trata de una proyección en 3D.
Para dibujar una superficie con \textit{plot\_surface} hay que generar una rejilla $(X_m,Y_m)$ y en cada uno de los puntos de esa rejilla calcular el valor de la superficie.
Para definir dicha retícula se necesitan dos matrices. Una de ellas $X_m$ contiene las coordenadas $x$ de los nodos de la retícula y la otra $Y_m$ las coordenadas $y$. Los elementos que ocupan la misma posición en ambas matrices, representan ---juntos--- un punto en el plano.
Matplotlib emplea dichas matrices como matrices de \emph{adyacencia}. Cada nodo,
$$(x_m(i,j),y_m(i,j))$$
aparecerá en la gráfica conectado por una arista a cada uno de sus cuatro puntos vecinos,
$$(x_m(i-1,j),y_m(i-1,j))$$,
$$(x_m(i,j-1),y_m(i,j-1))$$,
$$(x_m(i+1,j),y_m(i+1,j))$$,
$$(x_m(i,j+1),y_m(i,j+1))$$
Supongamos que empleamos las siguientes matrices, $X_m$ y $Y_m$ para definir una retícula sobre la que dibujar una superficie,
\switchcolumn
\subsection{Surfaces}
To draw a surface we will use the \textit{plot\-surface} method. As in the case of the \textit{scatter} method, we will have to previously create a figure and axes in 3 dimensions using \textit{subplots} and indicating that it is a 3D projection.
In order to draw a surface with \textit{plot\_surface} we must generate a grid $(X_m,Y_m)$ and at each of the points of this grid calculate the value of the surface.
To define such a grid, two matrices are needed. One of them $X_m$ contains the $x$ coordinates of the grid nodes and the other $Y_m$ the $y$ coordinates. Elements occupying the same position in both matrices represent - together - a point in the plane.
Matplotlib uses these matrices as adjacency matrices. Each node, $$(x_m(i,j),y_m(i,j))$$,
will appear in the graph connected by an edge to each of its four neighbouring points,
$$(x_m(i-1,j),y_m(i-1,j))$$,
$$(x_m(i,j-1),y_m(i,j-1))$$,
$$(x_m(i+1,j),y_m(i+1,j))$$,
$$(x_m(i,j+1),y_m(i,j+1))$$
Suppose we use the following matrices, $X_m$ and $Y_m$ to define a lattice on which to draw a surface,$z$.
\end{paracol}
\begin{align*}
X_m=\begin{pmatrix}
0&1&2&3\\
0&1&2&3\\
0&1&2&3\\
0&1&2&3
\end{pmatrix},& Y_m\begin{pmatrix}
0&0&0&0\\
1&1&1&1\\
2&2&2&2\\
3&3&3&3
\end{pmatrix}\xrightarrow[nodos]{posiciones}\begin{matrix}
(0,0)&-&(1,0)&-&(2,0)&-&(3,0)\\
\vert&&\vert&&\vert&&\vert\\
(0,1)&-&(1,1)&-&(2,1)&-&(3,1)\\
\vert&&\vert&&\vert&&\vert\\
(0,2)&-&(1,2)&-&(2,2)&-&(3,2)\\
\vert&&\vert&&\vert&&\vert\\
(0,3)&-&(1,3)&-&(2,3)&-&(3,3)
\end{matrix}
\end{align*}
\begin{minted}{python}
Axes3D.plot_surface(X, Y, Z, *, norm=None, vmin=None, vmax=None,
lightsource=None, **kwargs)
\end{minted}
\begin{paracol}{2}
La estructura de las matrices $X_m$ e $Y_m$ del ejemplo anterior, es la típica de las matrices de adyacencia de una retícula cuadrada; la matriz $X_m$ tiene la filas repetidas y la matriz $Y_m$ tiene repetidas la columnas. En el ejemplo las matrices son cuadradas y definen una retícula de $4\times 4$ nodos. En general, podemos definir una retícula rectangular de $m\times n$ nodos. En este caso las matrices empleadas para definir la retícula tendrían dimensión $m\times n$.
Para dibujar con Matplotlib superficies podemos en primer lugar definir la retícula a partir de dos vectores de coordenadas empleando el método de numpy \texttt{meshgrid}. En el ejemplo que acabamos de ver, hemos empleado una retícula que cubre el intervalo, $x\in[0,3]$ e $y\in[0,3]$. para definirlo creamos los vectores,
\begin{minted}{python}
x=np.arange(0,4)
x
Out[23]: array([0, 1, 2, 3])
y=np.arange(0,4)
y
Out[25]: array([0, 1, 2, 3])
\end{minted}
\switchcolumn
The structure of the $X_m$ and $Y_m$ matrices in the previous example is typical of the adjacency matrices of a square lattice; the $X_m$ matrix has repeated rows and the $Y_m$ matrix has repeated columns. In the example the matrices are square and define a lattice of $4\times 4$ nodes. In general, we can define a rectangular lattice of $times n$ nodes. In this case the matrices used to define the lattice would have dimension $m\times n$.
To draw with Matplotlib surfaces we can first define the grid from two coordinate vectors using the numpy method \texttt{meshgrid}. In the example we have just seen, we have used a grid covering the interval, $x\in[0,3]$ and $y\in[0,3]$. To define it we create the vectors,
\begin{minted}{python}
x=np.arange(0,4)
x
Out[23]: array([0, 1, 2, 3])
y=np.arange(0,4)
y
Out[25]: array([0, 1, 2, 3])
\end{minted}
\switchcolumn
A continuación empleamos el método \texttt{meshgrid} para construir las dos matrices de adyacencia. Numpy se encargará de repetir las filas y columnas necesarias,
\begin{minted}{python}
[Xm,Ym]=np.meshgrid(x,y)
Xm
Out[20]:
array([[0, 1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3]])
Ym
Out[21]:
array([[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]])
\end{minted}
\switchcolumn
Next, we use the method \texttt{meshgrid} to construct the two adjacency matrices. Numpy will take care of repeating the necessary rows and columns,
\begin{minted}{python}
[Xm,Ym]=np.meshgrid(x,y)
Xm
Out[20]:
array([[0, 1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3]])
Ym
Out[21]:
array([[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]])
\end{minted}
\switchcolumn
Una vez construidas las matrices de adyacencia, solo necesitamos una matriz de valores para $Z_m$. Si definimos por ejemplo,
\begin{minted}{python}
Zm=np.zeros(np.shape(Xm))
Zm
Out[35]:
array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
\end{minted}
\switchcolumn
Once the adjacency matrices are constructed, we only need a matrix of values for $Z_m$. If we define for example,
\begin{minted}{python}
Zm=np.zeros(np.shape(Xm))
Zm
Out[35]:
array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
\end{minted}
\switchcolumn
Podríamos representar la retícula plana de la figura \ref{fig:mesh}, empleando por ejemplo el comando \texttt{plot\_wireframe(Xm, Ym, Zm)}.
\switchcolumn
We could represent the flat grid of the figure \ref{fig:mesh}, using the command \texttt{plot\_wireframe(Xm, Ym, Zm)}.
\end{paracol}
\begin{figure}
\centering
\includegraphics[width=0.5\linewidth]{figuras/reticula.png}
\bicaption{Retícula plana}{Flat grid}
\label{fig:mesh}
\end{figure}
\begin{paracol} {2}
Una vez que hemos visto como construir una retícula rectangular sobre la que construir una superficie, veamos como dibujarla con un ejemplo. Supongamos que queremos dibujar la superficie,
\begin{equation*}
z=x^3+y^2
\end{equation*}
En la región del plano, $x\in[-1.5,1.5]$, $y\in[-2,2]$.
\switchcolumn
Now that we have seen how to construct a rectangular grid on which to build a surface, let's see how to draw it with an example. Suppose we want to draw the surface,
\begin{equation*}
z=x^3+y^2
\end{equation*}
In the region of the plane, $x\in[-1.5,1.5]$, $y\in[-2,2]$.
\switchcolumn
Igual que en el ejemplo inicial, lo primero que debemos hacer es construirnos una matrices de adyacencia que definan una retícula en la región de interés,
\begin{minted}{python}
x=np.linspace(-1.5,1.5,25)
y=np.linspace(-2,2,50)
[Xm,Ym]=np.meshgrid(x,y)
\end{minted}
\switchcolumn
As in the initial example, the first thing to do is to construct adjacency matrices that define a grid in the region of interest,
\begin{minted}{python}
x=np.linspace(-1.5,1.5,25)
y=np.linspace(-2,2,50)
[Xm,Ym]=np.meshgrid(x,y)
\end{minted}
\switchcolumn
Es interesante notar que la región de interés no es cuadrada y que las matrices de adyacencia tampoco los son ($50\times 25$). Además los puntos no están espaciados igual en los dos ejes.
A continuación obtenemos la matriz de coordenadas z, aplicando la función a los puntos de la retícula,
\begin{minted}{python}
Zm=Xm**3+Ym**2
\end{minted}
\switchcolumn
It is interesting to note that the region of interest is not square and that the adjacency matrices are not square either ($50\times 25$). Also the points are not equally spaced on the two axes.
Next we obtain the z-coordinate matrix by applying the function to the grid points,
\begin{minted}{python}
Zm=Xm**3+Ym**2
\end{minted}
\switchcolumn
Podemos representar la superfície usando el método \textit{wireframe} o el método \textit{surface}. En el primer caso se dibuja la superfície como una rejilla, figura \ref{fig:wireframe} y en el segundo como las caras rellenas de color de la retícula, figura \ref{fig:surface}.
Igualmente podemos representar una superficie con un mapa de color o de contornos en 2 dimensiones usando el el método \textit{contourf} o el método \textit{pcolor}. En este caso no se emplea \textit{subplot\_kw="projection": "3d"} porque no hace falta dibujar en el eje z, ya que se le atribuye un contorno o un color.
\switchcolumn
We can represent the surface using the \textit{wireframe} method or the \textit{surface} method. In the first case the surface is drawn as a grid, figure \ref{fig:wireframe}, and in the second as the colour-filled faces of the grid, figure \ref{fig:surface}.
We can also represent a surface with a color or contour map in 2 dimensions using the \textit{contourf} method or the \textit{pcolor} method. In this case, \textit{subplot\_kw=“projection”: “3d”} is not used because it is not necessary to draw on the z-axis, since a contour or a colour is assigned to it.
\end{paracol}
\begin{minted}{python}
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(1,100,1000)
y=np.linspace(1,100,1000)
[X,Y]=np.meshgrid(x,y)
Zm=X**2+Y**2
fig,(ax1,ax2)=plt.subplots(nrows=1,ncols=2,figsize=(15,10))
ax2.contourf(X,Y,Zm)
ax1.contour(X, Y, Zm)
\end{minted}
\begin{figure}
\centering
\begin{subfigure}{0.45\textwidth}
\includegraphics[width=8cm]{figuras/wireframe.png}
\bicaption{Función $z=x^3+y^2$ representada con \texttt{wireframe}}{Function $z=x^3+y^2$ represented with \texttt{wireframe}}\label{fig:wireframe}
\end{subfigure}
\begin{subfigure}{0.45\textwidth}
\includegraphics[width=8cm]{figuras/surface.png}
\bicaption{Función $z=x^3+y^2$ representada con \texttt{surf}}{Function $z=x^3+y^2$ represented with \texttt{surf}} \label{fig:surface}
\end{subfigure}
\bicaption{Comparación entre \texttt{wireframe} y \texttt{surface}}{Comparison between \texttt{wireframe} and \texttt{surface}}
\end{figure}
\begin{paracol}{2}
\section{Animaciones}
Matplotlib también proporciona una interfaz para generar animaciones utilizando el módulo \textit{animation}. Una animación es una secuencia de fotogramas en la que cada fotograma corresponde a un trazado sobre una figura.
\switchcolumn
\section{Animations}
Based on its plotting functionality, Matplotlib also provides an interface to generate animations using the \textit{animation} module. An animation is a sequence of frames where each frame corresponds to a plot on a figure.
\switchcolumn
Para crear una animación en python usando \textit{matplotlib.animation} seguiremos los siguientes pasos:
\begin{enumerate}
\item Inicializar los meta datos para la animación.
\item Inicializar el fondo de la animación.
\item Definir los objetos que van a ir cambiando en cada fotograma.
\end{enumerate}
\switchcolumn
To create an animation in python using \textit{matplotlib.animation} we will follow the following steps:
\begin{enumerate}
\item Initialise the meta data for the animation.
\item Initialise the background of the animation.
\item Define the objects that are going to change in each frame.
\end{enumerate}
\switchcolumn
\paragraph{Inicializar los metadatos}. Inicializar los meta datos para la animación creando un diccionario con ellos y pasándoselos al método que va a crear la animación \textit{writers}. Le indicamos tanto los metadatos como el número de frames por segundo con el parámetro \texttt{fps}.
\switchcolumn
\paragraph{Initialize the meta data.} Initialise the meta data for the animation by creating a dictionary of it and passing it to the method that will create the animation \textit{writers}.We indicate both the metadata and the number of frames per second with the parameter \texttt{fps}.
\end{paracol}
\begin{minted}{python}
FFMpegWriter=manimation.writers["ffmpeg"]
metadata = dict(title="GIF Test", artist ="Me",
comment="A red circle following a blue sine wave")
writer = FFMpegWriter(fps=15, metadata=metadata)
\end{minted}
\begin{paracol}{2}
\paragraph{Inicializar el fondo de la animación}, es decir aquellos elementos que no van a cambiar. Lo haremos definiendo una figura y todo aquello que va a permanecer constante durante la animación, por eso lo llamamos el fondo. En este caso es la curva del seno. También inicializamos el punto vacío rojo, al que le damos unas coordendas vacías, para que Python sepa que esas coordenadas se actualizarán posteriormente. Como las etiquetas no cambian también las ponemos aquí.
\switchcolumn
\paragraph{Initialise the background of the animation}, i.e. those elements that are not going to change. We will do this by defining a figure and everything that will remain constant during the animation, which is why we call it the background. In this case it is the sine curve. We also initialise the red empty point, to which we give empty coordinates, so that Python knows that these coordinates will be updated later. Since the labels don't change, we also put them here.
\end{paracol}
\begin{minted}{python}
fig =plt.figure()
n=1000
x=np.linspace(0, 6*np.pi,n)
y=np.sin(x)
sine_line, =plt.plot(x,y,"b")
red_circle,=plt.plot([],[],"ro",markersize=10)
plt.xlabel("x")
plt.ylabel("sin(x)")
\end{minted}
\begin{paracol}{2}
\paragraph{Definir los objetos que van a ir cambiando en cada fotograma}. Salvaremos un fichero, indicando qué figura vamos a salvar, el nombre del fichero (\texttt{movie\_test.mpg}) y la resolución de la figura en puntos por pulgada (dpi). En el bucle \textit{for} se actualiza repetidamente la figura para crear el movimiento, en cada iteración se actualiza la posición del punto rojo (usando \texttt{set\_data}). El método \texttt{grab\_frame} captura estos cambios y los muestra con los frames por segundo especificados anteriormente.
\switchcolumn
\paragraph{Define the objects that are going to change in each frame.} We will save a file, indicating which figure we are going to save, the name of the file (\texttt{movie\_test.mpg}) and the resolution of the figure in dots per inch (dpi). In the \textit{for} loop the figure is repeatedly updated to create the movement, in each iteration the position of the red dot is updated (using \texttt{set\_data}). The \texttt{grab\_frame} method captures these changes and displays them at the frames per second specified above.
\end{paracol}
\begin{minted}{python}
with writer.saving(fig,"movie_test.mp4",100):
for i in range(n):
x0=x[i]
y0=y[i]
red_circle.set_data([x0],[y0])
writer.grab_frame()
\end{minted}
\newpage
\section{Ejercicios}
\begin{enumerate}
\item Escribe una función que muestre paso a paso en una figura la trayectoria del tiro parabólico para $v_0=40$ (m/s) $\theta=45 $ grados y para $v_0=60$ (m/s) $\theta=60 $ grados. En cada instante se mostrará con un círculo rojo la posición (x, y).
\begin{align*}
x&=v_0 \cdot \cos(\theta) \cdot t \\
y&=v_0 \cdot \sin(\theta) \cdot t -\frac{1}{2}\cdot g \cdot t^2
\end{align*}
Añade el nombre de cada eje y el título de la figura.
\item Usa únicamente una sola figura para representar en diferentes paneles las siguientes funciones.
\begin{itemize}
\item $y=e^{-x^2}$ en el intervalo $[-2,2]$ empleando $100$ datos equiespaciados
\item $y=e^{-((\frac{x}{2})^2))}$
\item $y=e^{-((2x)^2)}$
\item La función $y=e^{-((2x)^2)}$ pero en escala logarítmica
\end{itemize}
\item Crear una función dibujatriangul que tenga como argumento de entrada los 3 vértices de un triángulo y devuelva una figura con el triángulo dibujado.
\item Crea una función \emph{dibujaMUC} que dibuje la trayectoria circular de una partícula conociendo su velocidad angular $\omega$ y el radio de giro $r$.
Las ecuaciones cartesianas son:
\begin{align*}
x&=r\cos(\omega \cdot t)\\
y&=r\sin (\omega \cdot t)
\end{align*}
\begin{itemize}
\item Añadir a la trayectoria en cada punto el vector velocidad con el comando quiver mediante las ecuaciones de la velocidad:
\begin{align*}
v_x&=-r\cdot \omega \cdot \sin(\omega \cdot t)\\
v_x&=r\cdot \omega \cdot \cos(\omega \cdot t)
\end{align*}
\end{itemize}
\item Crea una función que tenga como parámetros de entrada el radio $r$ y
la velocidad angular $\omega$ y dibuje la trayectoria en 3 dimensiones de una partícula que describe un MCU en el plano XY moviéndose en el eje z con una velocidad constante $v_z$.
\item Crea una función que represente el tiro parabólico en 3D sabiendo
que la función tiene como entrada los ángulos $\psi$ y $\theta$ , de acuerdo con las siguientes expresiones:
\begin{align*}
x&=v_0 \cdot \cos(\psi)\cdot \cos(\theta) \cdot t \\
y&=v_0 \cdot \sin(\psi)\cdot \cos(\theta) \cdot t \\
z&=v_0 \cdot \sin(\theta) \cdot t- \frac{1}{2} \cdot g \cdot t^2
\end{align*}
\item Usando el Comando meshgrid, crea una retícula cuadrada en el intervalo $x = [-1, 1]$ e $y = [-2, 2]$ emplea para ello un paso de malla de valor $0.1$. Crea una matriz de ceros del tamaño de las matrices que definen la retícula. Representa, empleando el comando mesh, la matriz de ceros
creada sobre la retícula. Representa gráficamente la superficie $z = e^{-(x^2+y^2)}$.
\item Genera $1000$ números aleatorios distribuidos normalmente (usa para ello la función \emph{np.random.randn}. Usa la función \emph{plt.hist} para dibujar el histograma de los números aleatorios generados.
\begin{itemize}
\item Sepáralos en $10$ contenedores.
\item Crea un diagrama de barras de los datos del apartado anterior usando \emph{plt.bar}.
\item ¿Crees que la función \emph{np.random.randn} es una buena aproximación de una distribución normal?
\end{itemize}
\item Crea una función \emph{my\_poly\_plot(n,x)} que dibuje los polinomios $p(x)=x^k$ para $k=1,...,n$.
\item Supón que tienes tres puntos que forman las esquinas de un triángulo equilátero $P_1=(0,0)$, $P_2=(0.5,\frac{\sqrt{2}}{2})$ y $P_3=(1,0)$. Crea una función que:
\begin{itemize}
\item Genere un conjunto de $n$ puntos $p_i=(x_i,y_i)$ tales que $p_1=(0,0)$ y $p_{i+1}$ es el punto medio entre $p_i$ y $P_1$ con un $33\%$ de probabilidad, el punto medio entre $p_i$ y $P_2$ con un $33\%$ de probabilidad y el punto medio entre $p_i$ y $P_3$ con un $33\%$ de probabilidad.
\item Dibuje los puntos obtenidos en el plano.
\item Prueba la función para $n=100$ y $n=1000$ puntos.
\end{itemize}
\item El fichero de precipitaciones \textit{precip.dat} es un fichero de texto plano que contiene 14 columnas, la primera se corresponde con el campo \textbf{Año}, de la segunda a la decimotercera que contiene los datos de precipitación de cada mes (enero, febrero....noviembre, diciembre), la última columna contiene el campo \textbf{Precipitación Total Anual}. Las unidades de precipitación vienen dadas en mm/mes o mm/año, según el caso.
En el fichero \textit{precip.dat} hay dos tipos de errores:
\begin{itemize}
\item La precipitación de uno de los meses es muy superior a la precipitación total que debería corresponder a la suma de la precipitación mensual de ese año. Esto ocurre en dos años.
\item En otros cuatro años la suma total de la precipitación es diferente a la precipitación
acumulada o total para ese año. A diferencia de lo que ocurría en el caso (a), la diferencia
entre los valores de precipitación de los distintos meses no es muy grande.
\end{itemize}
El objetivo de este ejercicio es identificar los meses (y los años) en los que se da alguno de
estos dos errores y sustituirlo por el valor correcto. Para ello debes realizar las siguientes
operaciones:
\begin{enumerate}
\item Extrae las precipitaciones en cada uno de los meses. Asigna la información de la precipitación total anual en un array unidimensional y el resto de las
precipitaciones a una variable matricial.
\item Dibuja en una gráfica la evolución de la precipitación anual del mes de enero en los
diferentes años.
\item Dibuja en una única gráfica la evolución de la precipitación anual para cada uno de los meses, junto con el campo \textbf{Precipitación Total Anual}.
\item Crea un script que realice las siguientes operaciones:
\begin{enumerate}
\item Chequear, para cada año, si la columna de precipitación total corresponde a la suma total de las precipitaciones de los meses. Si no fuera así, el script debe identificar el tipo de error encontrado:
\begin{itemize}
\item Si la discrepancia entre la suma de todos los meses difiere mucho del dato de
\textbf{Precipitación Total Anual} (error tipo (a)), se debe calcular el valor correcto de
precipitación para ese mes, considerando que el dato de \textbf{Precipitación Total Anual}
es correcto.
\item Si el dato de \textbf{Precipitación Total Anual} no difiere mucho de la suma de las precipitaciones mensuales (error tipo (b)), considera que el dato de precipitación total es erróneo y sustitúyelo por el valor de esta suma.
\end{itemize}
\item El script debe incorporar la visualización por pantalla de lo siguiente: (1) año donde se ha detectado un error, (2) suma total mensual para ese año, (3) dato de precipitación total anual de ese año y (4) si el error es del tipo (a), el mes en el que se encuentra dicho error.
\item Además, el script debe crear un fichero de texto en el que se guarden los datos iniciales con los errores corregidos.
\end{enumerate}
\end{enumerate}
\end{enumerate}
\section{Test del curso 2020/21}
\begin{enumerate}
\item El movimiento de un cuerpo en el plano viene descrito por las siguientes ecuaciones,
\begin{align}
x(t) &= \sin(2 \pi \, \omega_1 t)\\
y(t) &= \cos(2 \pi \, \omega_2 t)\\
z(t) &= a\cos(2\pi \, \omega_1 t) \label{eq:3}
\end{align}
donde $x,y,z$ representan las coordenadas del cuerpo en el instante de tiempo $t$ medidas en metros, $w_1$ y $w_2$ son frecuencias fijas medidas en $rad\cdot s^{-1}$ y $a$ es una amplitud fija medida en metros.