<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Matplotlib 2016
requires ipython and ipyton-notebook packages
execute
Step1:  Above commands enable pylab environment => direct access to numpy, scipy and matplotlib. The option 'inline' results in plot outputs to be directly embedded in the Notebook. If this causes problems, remove the option 'inline'.
Step2:  A simple plotting example. Maybe some variations
Step3:  Alternatively, Matplotlib understands the MATLAB syntax, e.g., for the above command (does not work with 'inline' enabled)
Step4:  Available settings for a plot can be found this way (does not work with 'inline' enabled)
Step5:  Some more commands for plot formatting
Step6:  Let's switch to the Qt backend for plotting
Step7:  Figures can be saved in a number of output formats such as Postscript
Step8:  Alternatively, you can also save figures in PNG bitmap and PDF vector formats. (Note that some export formats may not be supported on your platform.)
Step9:  You can close an open figure using its handle
Step10:  Or in MATLAB style, close all open figures
Step11:  Let's do a figure with several subpanels
Step12:  Especially for figures with multiple subpanels it may be advisable to increase the figure size somewhat. Do this by using function arguments in the figure() call
Step13:  By using Numpy arrays, Matplotlib can conveniently be used as a function ploting program
Step14:  Certainly, you can do plots with logarithmic scale
Step15:  Let's add grid lines
Step16:  Analogously, you can use semilogy() and loglog() for plots with log y-axis and loglog plots.
Step17:  Anybody bar charts?
Step18:  Let's pimp the plot a little
Step19:  For horizontal bar charts, you would use barh().
Where there are bars, there should be pies
Step20:  As you will have seen, we retrieved handles to the individual pie slices. Let's do something with them
Step21:  Matplotlib also offers quiver() plots which are illustrated in the following example (taken from http
Step22:  Polar plots are also nicely illustrated on the very same homepage
Step23:  Contour plots are well suited for visualization of three-dimensional data sets
Step24:  A similar yet distint representation is provided by pcolormesh().
Step25:  Compare the two figures, spot the similarities and differences.
Matplotlib sports an add-on module for 3D graphics as detailed below. First, we need to import this module.
Step26:  Let's switch to the Qt backend for 3D plotting
Step27:  Then, we can play around.
Step28:  Try moving and rotating the (so far empty) plot in three dimensions. Once you have calmed down, let's populate the plot with some data
Step29:  In addition to the above 3D scatter plot, other plot types are supported, such as 3D surface plots
Step30:  Try some other colormaps such as cm.bone, cm.spring or cm.cool (once more, these are the MATLAB color schemes).
We do one more example that shows the use of 3D surface and 3D contour plots (as opposed to the 2D contour plots above).
Step31:  Let's display the same data in contour representation
Step32:  Style sheets
Step33:  There are several predefinded style sheets for matplotlib. You can show all availible styles by typing
Step34:  to pick one of them, type e.g.
Step35:  and your plots will look similar to those created with ggplot2 in R
Step36:  Exercises for Numpy and Matplotlib
Exercise 1
Plot the following functions into individual subplots
Step37:  Exercise 2
generate two 1D-arrays $A$ and $B$ of size $N$ containing Gaussian random numbers
Step38:  Check whether they are correlated using a scatter plot
Step39:  Plot their 2D density as a contour plot (hint
<ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
Explanation: Matplotlib 2016
requires ipython and ipyton-notebook packages
execute: ipython3 notebook
check out this resource for Matplotlib: http://matplotlib.org/gallery.html
End of explanation
xv=[1,2,3,4]; yv=[5,1,4,0]
plt.plot(xv,yv);
Explanation: Above commands enable pylab environment => direct access to numpy, scipy and matplotlib. The option 'inline' results in plot outputs to be directly embedded in the Notebook. If this causes problems, remove the option 'inline'.
End of explanation
plt.plot(xv,yv,'ro');
myplot=plt.plot(xv,yv,'k--');
plt.setp(myplot,linewidth=3.0,marker='+',markersize=30);
Explanation: A simple plotting example. Maybe some variations:
End of explanation
myplot=plt.plot(xv,yv,'k--');
plt.setp(myplot,'linewidth',3.0,'marker','+','markersize',30);
Explanation: Alternatively, Matplotlib understands the MATLAB syntax, e.g., for the above command (does not work with 'inline' enabled):
End of explanation
plt.setp(myplot)
Explanation: Available settings for a plot can be found this way (does not work with 'inline' enabled):
End of explanation
plt.axis()
plt.axis([0.5,4.5,-0.5,5.5])
Explanation: Some more commands for plot formatting:
End of explanation
%matplotlib
plt.ioff() # deactivates 'interactive' mode
fig = plt.figure()
ti=plt.title('Very important data')
xl=plt.xlabel('time'); yl=plt.ylabel('value')
plt.setp(xl,fontweight='bold');
plt.show()
Explanation: Let's switch to the Qt backend for plotting
End of explanation
fig.savefig('foo.ps', dpi=600, format='ps',orientation='landscape')
Explanation: Figures can be saved in a number of output formats such as Postscript:
End of explanation
fig.savefig('foo.png', dpi=600, format='png',orientation='landscape')
fig.savefig('foo.pdf', dpi=600, format='pdf',orientation='landscape')
Explanation: Alternatively, you can also save figures in PNG bitmap and PDF vector formats. (Note that some export formats may not be supported on your platform.)
End of explanation
plt.close(fig)
Explanation: You can close an open figure using its handle:
End of explanation
plt.close('all')
Explanation: Or in MATLAB style, close all open figures:
End of explanation
fig = plt.figure()
plt.subplot(2,1,1)
plt.plot(xv,yv,'b-')
plt.subplot(2,1,2)
plt.plot(yv,xv,'ro')
plt.show()
plt.close(fig)
Explanation: Let's do a figure with several subpanels:
End of explanation
# switch back to inline mode
%matplotlib inline
fig2=plt.figure(figsize=(10,10))
plt.subplot(2,1,1)
plt.plot(xv,yv,'b-')
plt.subplot(2,1,2)
plt.plot(yv,xv,'ro');
Explanation: Especially for figures with multiple subpanels it may be advisable to increase the figure size somewhat. Do this by using function arguments in the figure() call:
End of explanation
xv=np.arange(-10,10.5,0.5); xv
plt.plot(xv,2*xv**3-5*xv**2+7*xv)
plt.plot(xv,2000*np.cos(xv),'r--')
plt.text(-10,-2800,'curve A')
plt.text(3,1500,'curve B');
Explanation: By using Numpy arrays, Matplotlib can conveniently be used as a function ploting program:
End of explanation
xv_lin=np.arange(-3,3.01,0.02)
xv=10.**xv_lin
plt.semilogx(xv,np.exp(-xv/0.01)+0.5*np.exp(-xv/10)+0.2*np.exp(-xv/200));
Explanation: Certainly, you can do plots with logarithmic scale:
End of explanation
plt.semilogx(xv,np.exp(-xv/0.01)+0.5*np.exp(-xv/10)+0.2*np.exp(-xv/200))
plt.grid(color='k')
Explanation: Let's add grid lines:
End of explanation
plt.semilogy(xv,np.exp(-xv/0.01)+0.5*np.exp(-xv/10)+0.2*np.exp(-xv/200))
Explanation: Analogously, you can use semilogy() and loglog() for plots with log y-axis and loglog plots.
End of explanation
xv=[0.5,1.5,2.5,3.5]; yv=[2,5,1,6]
mybar=plt.bar(xv, yv, width=1, yerr=0.5, facecolor='b')
Explanation: Anybody bar charts?
End of explanation
mybar=plt.bar(xv, yv, width=1, yerr=0.5);
plt.xticks(xv, ['A','B','C','D'])
plt.setp(mybar, facecolor='r', edgecolor='w');
Explanation: Let's pimp the plot a little:
End of explanation
plt.figure(figsize=(5,5))
handles=plt.pie([1,2,3,4], explode=[0.2,0,0,0], shadow=True, labels=['A','B','C','D']);
handles
Explanation: For horizontal bar charts, you would use barh().
Where there are bars, there should be pies:
End of explanation
plt.figure(figsize=(5,5))
handles=plt.pie([1,2,3,4], explode=[0.2,0,0,0], shadow=True, labels=['A','B','C','D'])
plt.setp(handles[0] [0], color='y')
plt.setp(handles[1] [0], text='Blubber');
Explanation: As you will have seen, we retrieved handles to the individual pie slices. Let's do something with them:
End of explanation
n=8; X,Y=np.mgrid[0:n,0:n]
T=np.arctan2(Y-n/2.0,X-n/2.0)
R=10+np.sqrt((Y-n/2.0)**2+(X-n/2.0)**2)
U,V=R*np.cos(T),R*np.sin(T)
plt.axes([0.025,0.025,0.95,0.95])
plt.quiver(X,Y,U,V,R,alpha=.5)
plt.quiver(X,Y,U,V, edgecolor='k', facecolor= 'None', linewidth=.5);
Explanation: Matplotlib also offers quiver() plots which are illustrated in the following example (taken from http://www.loria.fr/~rougier/teaching/matplotlib/):
End of explanation
ax=plt.axes([0.025,0.025,0.95,0.95],polar=True)
N=20; theta=np.arange(0.0,2*np.pi,2*np.pi/N)
radii=10*np.random.rand(N)
width=np.pi/4*np.random.rand(N)
bars=plt.bar(theta,radii,width=width,bottom=0.0)
for r,bar in zip(radii,bars):
    bar.set_facecolor( plt.cm.jet(r/10.))
    bar.set_alpha(0.5)
Explanation: Polar plots are also nicely illustrated on the very same homepage:
End of explanation
xv=np.linspace(-10,10,100); yv=xv
X,Y=np.meshgrid(xv,yv)
Z=np.exp(-((X-1)**2/2/0.5**2)-((Y+2)**2/2/3**2))
Z=Z+1.5*np.exp(-((X-5)**2/2/4**2)-((Y-6)**2/2/3**2))
plt.contourf(X,Y,Z,10,alpha=0.5,cmap=plt.cm.hot)
C=plt.contour(X,Y,Z,10,colors='black', linewidth=0.5)
plt.clabel(C,inline=1,fontsize=10);
Explanation: Contour plots are well suited for visualization of three-dimensional data sets:
End of explanation
plt.pcolormesh(X,Y,Z,alpha=0.5,cmap=plt.cm.hot)
plt.axis([-5,10,-8,10]);
Explanation: A similar yet distint representation is provided by pcolormesh().
End of explanation
from mpl_toolkits.mplot3d import Axes3D
Explanation: Compare the two figures, spot the similarities and differences.
Matplotlib sports an add-on module for 3D graphics as detailed below. First, we need to import this module.
End of explanation
%matplotlib
plt.ioff()
Explanation: Let's switch to the Qt backend for 3D plotting
End of explanation
plt.close('all'); fig=plt.figure()
ax=Axes3D(fig)
plt.show()
Explanation: Then, we can play around.
End of explanation
plt.close('all'); fig=plt.figure()
ax=Axes3D(fig)
import random as rn
xv=[]; yv=[]; zv=[]
for c in range(100):
   xv.append(rn.random()); yv.append(rn.random())
   zv.append(rn.random())
ax.scatter(xv,yv,zv)
plt.show()
Explanation: Try moving and rotating the (so far empty) plot in three dimensions. Once you have calmed down, let's populate the plot with some data:
End of explanation
plt.close('all'); fig=plt.figure()
ax=Axes3D(fig)
xv=np.linspace(-10,10,100); yv=np.linspace(-10,10,100)
cx,cy=np.meshgrid(xv,yv)
cz=0.5*cx+np.exp(-cy**2)
tilt=ax.plot_surface(cx,cy,cz,linewidth=0, cmap=plt.cm.jet);
plt.show()
Explanation: In addition to the above 3D scatter plot, other plot types are supported, such as 3D surface plots:
End of explanation
plt.close('all'); fig=plt.figure()
ax=Axes3D(fig)
xv=np.linspace(-10,10,100); yv=np.linspace(-10,10,100)
cx,cy=np.meshgrid(xv,yv)
cz=0*cx
def gauss2D(x0,y0,sigx=1,sigy=1,height=1):
   z=height*np.exp(-((cx-x0)**2/2/sigx**2)-((cy-y0)**2/2/sigy**2))
   return z
cz=cz+gauss2D(-2,3)
cz=cz+gauss2D(2,4,2,3)
ax.plot_surface(cx,cy,cz,linewidth=0,cstride=2, rstride=2,cmap=plt.cm.jet)
plt.show()
Explanation: Try some other colormaps such as cm.bone, cm.spring or cm.cool (once more, these are the MATLAB color schemes).
We do one more example that shows the use of 3D surface and 3D contour plots (as opposed to the 2D contour plots above).
End of explanation
plt.close('all'); fig=plt.figure()
ax=Axes3D(fig)
ax.contour(cx,cy,cz,cstride=2,rstride=2, cmap=plt.cm.jet)
plt.show()
Explanation: Let's display the same data in contour representation:
End of explanation
%matplotlib inline
plt.close('all')
Explanation: Style sheets
End of explanation
plt.style.available
Explanation: There are several predefinded style sheets for matplotlib. You can show all availible styles by typing
End of explanation
plt.style.use('ggplot')
Explanation: to pick one of them, type e.g.
End of explanation
x = np.linspace(0,10,100)
y = np.sin(x)
plt.plot(x,y)
Explanation: and your plots will look similar to those created with ggplot2 in R
End of explanation
%matplotlib inline
Explanation: Exercises for Numpy and Matplotlib
Exercise 1
Plot the following functions into individual subplots:
$f(x) = e^{-\alpha x^2},\quad g(x) = \alpha x^3-5x^2, \quad h(x) = \mathrm{erf}(x)$
with $\alpha \in {0.1,0.5,1}$
hint: use scipy for the definition of $\mathrm{erf}(x)$
End of explanation
N = 1e4
Explanation: Exercise 2
generate two 1D-arrays $A$ and $B$ of size $N$ containing Gaussian random numbers
End of explanation
%matplotlib inline
Explanation: Check whether they are correlated using a scatter plot
End of explanation
%matplotlib
plt.ioff()
Explanation: Plot their 2D density as a contour plot (hint: the density can be obtained from a histogram)
Plot the density as 3D surface plot
End of explanation
<END_TASK>