Numpy Matplotlib
Matplotlib is a plotting library for Python. It can be used in conjunction with NumPy, providing an efficient open-source alternative to MatLab. It can also be used with graphical toolkits like PyQt and wxPython.
Installation via pip3:
pip3 install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple
On Linux systems, you can also use the Linux package manager to install:
* Debian / Ubuntu:
sudo apt-get install python-matplotlib
* Fedora / Redhat:
sudo yum install python-matplotlib
After installation, you can use the `python -m pip list` command to check if the matplotlib module is installed.
$ pip3 list | grep matplotlib matplotlib 3.3.0
### Example
## Example
import numpy as np from matplotlib import pyplot as plt x = np.arange(1,11)y = 2 * x + 5 plt.title("Matplotlib demo")plt.xlabel("x axis caption")plt.ylabel("y axis caption")plt.plot(x,y)plt.show()
In the above example, the `np.arange()` function creates the values for the x-axis. The corresponding values for the y-axis are stored in another array object `y`. These values are plotted using the `plot()` function from the `pyplot` submodule of the matplotlib package.
The graph is displayed by the `show()` function.
!(#)
### Displaying Chinese in Graphs
Matplotlib does not support Chinese characters by default. We can use the following simple method to resolve this.
Here we use Source Han Sans, an open-source font released by Adobe and Google.
Official website: [https://source.typekit.com/source-han-serif/cn/](https://source.typekit.com/source-han-serif/cn/)
GitHub address: [https://github.com/adobe-fonts/source-han-sans/tree/release/OTF/SimplifiedChinese](https://github.com/adobe-fonts/source-han-sans/tree/release/OTF/SimplifiedChinese)
After opening the link, select one from there:
!(#)
You can also download it from the cloud drive: [https://pan.baidu.com/s/10-w1JbXZSnx3Tm6uGpPGOw](https://pan.baidu.com/s/10-w1JbXZSnx3Tm6uGpPGOw), extraction code: yxqu.
You can download an OTF font, for example, `SourceHanSansSC-Bold.otf`, and place this file in the directory where your code is currently executing:
Place the `SourceHanSansSC-Bold.otf` file in the directory where your code is currently executing:
## Example
import numpy as np from matplotlib import pyplot as plt import matplotlib zhfont1 = matplotlib.font_manager.FontProperties(fname="SourceHanSansSC-Bold.otf")x = np.arange(1,11)y = 2 * x + 5 plt.title(" - Test", fontproperties=zhfont1)plt.xlabel("x axis", fontproperties=zhfont1)plt.ylabel("y axis", fontproperties=zhfont1)plt.plot(x,y)plt.show()
The execution output is as shown in the following figure:
!(#)
> Additionally, we can use the system's fonts:
>
> from matplotlib import pyplot as plt import matplotlib a=sorted([f.name for f in matplotlib.font_manager.fontManager.ttflist])for i in a: print(i)
> This prints all the registered names in your `font_manager`'s `ttflist`. Find a Chinese font you like, for example: STFangsong (FangSong), then add the following code:
>
> plt.rcParams['font.family']=['STFangsong']
As an alternative to a line plot, you can display discrete values by adding a format string to the `plot()` function. The following formatting characters can be used.
| Character | Description |
| --- | --- |
| `'-'` | Solid line style |
| `'--'` | Dashed line style |
| `'-.'` | Dash-dot line style |
| `':'` | Dotted line style |
| `'.'` | Point marker |
| `','` | Pixel marker |
| `'o'` | Circle marker |
| `'v'` | Triangle down marker |
| `'^'` | Triangle up marker |
| `'<'` | Triangle left marker |
| `'>'` | Triangle right marker |
| `'1'` | Tri_down marker |
| `'2'` | Tri_up marker |
| `'3'` | Tri_left marker |
| `'4'` | Tri_right marker |
| `'s'` | Square marker |
| `'p'` | Pentagon marker |
| `'*'` | Star marker |
| `'h'` | Hexagon1 marker |
| `'H'` | Hexagon2 marker |
| `'+'` | Plus marker |
| `'x'` | X marker |
| `'D'` | Diamond marker |
| `'d'` | Thin_diamond marker |
| `'|'` | Vline marker |
| `'_'` | Hline marker |
Here are the abbreviations for colors:
| Character | Color |
| --- | --- |
| `'b'` | Blue |
| `'g'` | Green |
| `'r'` | Red |
| `'c'` | Cyan |
| `'m'` | Magenta |
| `'y'` | Yellow |
| `'k'` | Black |
| `'w'` | White |
To display circles representing points instead of the lines in the example above, use `'ob'` as the format string in the `plot()` function.
## Example
import numpy as np from matplotlib import pyplot as plt x = np.arange(1,11)y = 2 * x + 5 plt.title("Matplotlib demo")plt.xlabel("x axis caption")plt.ylabel("y axis caption")plt.plot(x,y,"ob")plt.show()
The execution output is as shown in the following figure:
!(#)
### Plotting a Sine Wave
The following example uses matplotlib to generate a sine wave plot.
## Example
import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 3 * np.pi, 0.1)y = np.sin(x)plt.title("sine wave form")plt.plot(x, y)plt.show()
The execution output is as shown in the following figure:
!(#)
### subplot()
The `subplot()` function allows you to plot different things in the same figure.
The following example plots sine and cosine values:
## Example
import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 3 * np.pi, 0.1)y_sin = np.sin(x)y_cos = np.cos(x)plt.subplot(2, 1, 1)plt.plot(x, y_sin)plt.title('Sine')plt.subplot(2, 1, 2)plt.plot(x, y_cos)plt.title('Cosine')plt.show()
The execution output is as shown in the following figure:
!(#)
### bar()
The `pyplot` submodule provides the `bar()` function to generate bar charts.
The following example generates a bar chart for two sets of x and y arrays.
## Example
from matplotlib import pyplot as plt x = [5,8,10]y = [12,16,6]x2 = [6,9,11]y2 = [6,15,7]plt.bar(x, y, align = 'center')plt.bar(x2, y2, color = 'g', align = 'center')plt.title('Bar graph')plt.ylabel('Y axis')plt.xlabel('X axis')plt.show()
The execution output is as shown in the following figure:
!(#)
### numpy.histogram()
The `numpy.histogram()` function is a graphical representation of the frequency distribution of data. Rectangles of equal horizontal size correspond to class intervals, called bins, and the variable `height` corresponds to frequency.
The `numpy.histogram()` function takes the input array and bins as two arguments. The consecutive elements in the bin array are used as boundaries for each bin.
## Example
import numpy as np a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])np.histogram(a,bins = [0,20,40,60,80,100])hist,bins = np.histogram(a,bins = [0,20,40,60,80,100])print(hist)print(bins)
The output is:
### plt()
Matplotlib can convert the numerical representation of a histogram into a graph. The `plt()` function from the `pyplot` submodule takes an array containing the data and the bin array as arguments and converts it into a histogram.
## Example
from matplotlib import pyplot as plt import numpy as np a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])plt.hist(a, bins = [0,20,40,60,80,100])plt.title("histogram")plt.show()
The execution output is as shown in the following figure:
!(#)
> More references for Matplotlib:
>
>
> > > * (http://matplotlib.sourceforge.net/users/index.html)
> * (http://matplotlib.sourceforge.net/faq/index.html)
> * (http://matplotlib.sourceforge.net/users/screenshots.html)
YouTip