If you want to run it in google colaboratory here
matplotlib/mat_nb.ipynb)
Author’s environment
The author’s OS is macOS, and the options are different from Linux and Unix commands.
! sw_vers
ProductName: Mac OS X
ProductVersion: 10.14.6
BuildVersion: 18G6020
Python -V
Python 3.7.3
Import the basic libraries and check their versions.
%matplotlib inline
%config InlineBackend.figure_format ='svg'import matplotlib
import matplotlib.pyplot as plt
import scipy
import numpy as np
print('matplotlib version :', matplotlib.__version__)
print('scipy version :', scipy.__version__)
print('numpy version :', np.__version__)
matplotlib version : 3.0.3
scipy version : 1.4.1
numpy version : 1.16.2
Write a simple graph.
Let’s write a function $y = \sin x$. There are various maniacal ways to use this function, but in my work in data analysis, I feel that I use it most often in this form. Setting up the grid and labels is important, and I think it depends on your environment whether you can use tex in matplotlib or not.
plt.grid()
plt.title()
plt.xlabel()
plt.ylabe()
plt.xlim()
plt.legend()
x = np.linspace(0,10,100)
y = np.sin(x)
plt.grid()
plt.title("sin function")
plt.xlabel("$x$")
plt.ylabel("$y = \\sin(x)$")
plt.xlim(0,8)
plt.ylim(-1.2,1.2)
plt.plot(x,y,label="$y=\\sin x$")
plt.legend()
Although it is not that frequent, let’s try to draw a three-dimensional graph. Data analysis has hundreds of dimensions, but the number of dimensions that we can understand with our human senses is barely three. To be honest, I have a hard time even with 3 dimensions.
We will use a module called mplot3d. Also, specific to 3D graphs is the use of a numpy function called meshgrid.
Normally, to plot the plane $ z = x + y$ in $xyz$ space, the number of elements in $x$ and $y$ is determined by $N(x) \times N(y)$. Normally, you need to create an array for this amount, but meshgrid will automatically create it for you.
Let’s look at an example.
x = np.array([i for i in range(5)])
y = np.array([i for i in range(5)])
print('x :', x)
print('y :', y)
print()
xx, yy = np.array(np.meshgrid(x, y))
print('xx :', xx)
print()
print('yy :', yy)
/Users/hiroshi/anaconda3/lib/python3.7/site-packages/matplotlib/figure.py:445: UserWarning: Matplotlib is currently using module:// ipykernel.pylab.backend_inline, which is a non-GUI backend, so cannot show the figure.
% get_backend())