English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NumPy Matplotlib

pip3 Installation:

pip install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple

Linux systems can also install using the Linux package manager:

Debian / Ubuntu:

sudo apt-get install python-matplotlib

Fedora / Redhat:

sudo yum install python-matplotlib

After installation, you can use 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 sub-module of the matplotlib software package.

The graphic is displayed by the show() function.

Chinese display in graphics

Matplotlib does not support Chinese by default, and we can solve it with the following simple method.

Here we use Source Han Sans, which is an open-source font jointly launched 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, just select one in it:

You can download an OTF font, such as SourceHanSansSC-Bold.otf, place the file in the current executing code file:

SourceHanSansSC-Bold.otf file is placed in the current executing code file:

 import numpy as np 
 from matplotlib import pyplot as plt 
 import matplotlib
  
 # fname is the path to the downloaded font library, note that SourceHanSansSC-Bold.otf font path
 zhfont1 =matplotlib.font_manager.FontProperties(fname="SourceHanSansSC-Bold.otf") 
  
 x = np.arange(1,11) 
 y = 2 * x + 5 
 plt.title("Vertical goods - Test", fontproperties=zhfont1) 
  
 # fontproperties sets Chinese display, fontsize sets font size
 plt.xlabel("x axis", fontproperties=zhfont1)
 plt.ylabel("y axis", fontproperties=zhfont1)
 plt.plot(x,y) 
 plt.show()

In addition, we can also use the 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)

Print all the names registered in your font_manager's ttflist, find a Chinese font such as: STFangsong (Fangsong), and then add the following code:

plt.rcParams['font.family']=['STFangsong']

As an alternative to a linear plot, discrete values can be displayed by adding a format string to the plot() function. The following formatting characters can be used.

CharacterDescription
'-'Solid line style
'--'Dashed line style
'-.'Dotted style
':'Dashed style
'.'Dot marker
,','Pixel marker
'o'Circle marker
'v'Inverted triangle marker
'^'Right triangle marker
'<'Left triangle marker
'>'Right triangle marker
'1'Down arrow marker
'2'Up arrow marker
'3'Left arrow marker
'4'Right arrow marker
's'Square marker
'p'Pentagonal marker
'*'Star marker
'h'Hexagonal marker 1
'H'Hexagonal marker 2
'+'Plus sign marker
'x'X marker
'D'Diamond marker
'd'Narrow diamond marker
'|'Vertical line marker
'_'Horizontal line marker

The following are the abbreviations for colors:

CharacterColor
'b'Blue
'g'Green
'r'Red
'c'Cyan
'm'Magenta
'y'Yellow
'k'Black
'w'White

To display circles to represent points instead of lines in the above example, use ob as the format string in the plot() function.

 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 shown in the figure below:

Draw the sine wave

The following example uses matplotlib to generate a sine wave chart.

 import numpy as np 
 import matplotlib.pyplot as plt 
 # Calculate the x and y coordinates of the points on the sine curve
 x = np.arange(0, 3 * np.pi, 0.1) 
 y = np.sin(x)
 plt.title('sine waveform') 
 # Use matplotlib to draw points
 plt.plot(x, y) 
 plt.show()

The execution output is shown in the figure below:

subplot()

The subplot() function allows you to draw different things on the same graph.

The following example draws sine and cosine values:

 import numpy as np 
 import matplotlib.pyplot as plt 
 # Calculate the x and y coordinates of the points on the sine and cosine curves 
 x = np.arange(0, 3 * np.pi, 0.1) 
 y_sin = np.sin(x) 
 y_cos = np.cos(x) 
 # Establish a subplot grid, height is 2, width is 1 
 # Activate the first subplot
 plt.subplot(2, 1, 1) 
 # Draw the first image 
 plt.plot(x, y_sin) 
 plt.title('Sine') 
 # Activate the second subplot and draw the second image
 plt.subplot(2, 1, 2) 
 plt.plot(x, y_cos) 
 plt.title('Cosine') 
 # Display the image
 plt.show()

The execution output is shown in the figure below:

bar()

The pyplot sub-module provides the bar() function to generate bar charts.

The following example generates a bar chart of two groups of x and y arrays.

 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 shown in the figure below:

numpy.histogram()

The numpy.histogram() function is a graphical representation of the frequency distribution of the data. Rectangles of equal horizontal dimensions corresponding to the class interval, called bins, and the variable height corresponds to the frequency.

The numpy.histogram() function takes the input array and bin as two parameters. The continuous elements in the bin array are used as the boundaries of each bin.

 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 result is:

 [3 4 5 2 1]
 [ 0 20 40 60 80 100]

plt()

Matplotlib can convert the numeric representation of histograms into graphics. The plt() function of the pyplot sub-module takes an array containing data and bin arrays as parameters and converts it into a histogram.

 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 shown in the figure below:

More references for Matplotlib:

User Guide Frequently Asked Questions and Answers Screenshot