NumPy Matplotlib
Matplotlib is a plotting library for Python. It can be used in conjunction with NumPy to provide an efficient open-source alternative to MatLab. It can also be used with graphical toolkits such as PyQt and wxPython.
pip3 installation:
pip3 install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple
Linux systems 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
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 values on the x-axis. The corresponding values on the y-axis are stored in another array object y. These values are plotted using the plot() function of the pyplot submodule of the matplotlib package.
The graph is displayed by the show() function.
Chinese Display in Graphs
Matplotlib does not support Chinese by default, but we can solve this with a simple method.
Here we use Source Han Sans, an open-source font by Adobe and Google.
Official website: https://source.typekit.com/source-han-serif/cn/
GitHub address: https://github.com/adobe-fonts/source-han-sans/tree/release/OTF/SimplifiedChinese
After opening the link, choose one:
You can also download from a cloud drive: https://pan.baidu.com/s/10-w1JbXZSnx3Tm6uGpPGOw, extraction code: yxqu
.
Download an OTF font, such as SourceHanSansSC-Bold.otf, and place the file in the current execution code file:
Example
import numpy as np
from matplotlib import pyplot as plt
import matplotlib
# fname is the path to your font library, note the path to the SourceHanSansSC-Bold.otf font
zhfont1 = matplotlib.font_manager.FontProperties(fname="SourceHanSansSC-Bold.otf")
x = np.arange(1,11)
y = 2 * x + 5
plt.title("tutorialpro.org - Test", fontproperties=zhfont1)
# fontproperties to set Chinese display, fontsize to set font size
plt.xlabel("x axis", fontproperties=zhfont1)
plt.ylabel("y axis", fontproperties=zhfont1)
plt.plot(x,y)
plt.show()
The execution output result is as follows:
>
Additionally, we can use system 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)
Prints all registered names in your font_manager's ttflist. Find a Chinese font like STFangsong (Fangsong), then add the following code:
plt.rcParams['font.family'] = ['STFangsong']
As an alternative to a line graph, discrete values can be displayed 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 line 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()
Execution output is shown in the following image:
### Drawing a Sine Wave
The following example generates a sine wave plot using matplotlib.
## Example
import numpy as np import matplotlib.pyplot as plt
Calculate the x and y coordinates for points on a sine curve
x = np.arange(0, 3 * np.pi, 0.1) y = np.sin(x) plt.title("Sine wave form")
Use matplotlib to plot the points
plt.plot(x, y) plt.show()
Execution output is shown in the following image:
### subplot()
The subplot() function allows you to draw different things in the same figure.
The following example draws sine and cosine values:
## Example
import numpy as np import matplotlib.pyplot as plt
Calculate the x and y coordinates for points on sine and cosine curves
x = np.arange(0, 3 * np.pi, 0.1) y_sin = np.sin(x) y_cos = np.cos(x)
Create a subplot grid with height 2 and width 1
Activate the first subplot
plt.subplot(2, 1, 1)
Plot the first image
plt.plot(x, y_sin) plt.title('Sine')
Activate the second subplot and plot the second image
plt.subplot(2, 1, 2) plt.plot(x, y_cos) plt.title('Cosine')
Show the figure
plt.show()
Execution output is shown in the following image:
### bar()
The pyplot submodule provides the bar() function to generate bar charts.
The following example generates bar charts 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, align='center') plt.title('Bar graph') plt.ylabel('Y axis') plt.xlabel('X axis') plt.show()
Execution output is shown in the following image:
```python
plt.bar(x2, y2, color='g', align='center')
plt.title('Bar graph')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()
The output result is shown in the following figure:
numpy.histogram()
The numpy.histogram() function is a graphical representation of the frequency distribution of data. Equal-sized rectangles along the horizontal axis correspond to class intervals, known as bins, with the variable height representing frequency.
The numpy.histogram() function takes the input array and bins as two parameters. Consecutive elements in the bins array serve as the 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:
[3 4 5 2 1]
[ 0 20 40 60 80 100]
plt()
Matplotlib can convert the numerical representation of a histogram into a graphical form. The plt() function from the pyplot submodule takes arrays containing data and bin arrays as arguments and converts them 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 output result is shown in the following figure:
For more information on Matplotlib, refer to: