[NỘI DUNG BÀI VIẾT ĐƯỢC CẬP NHẬT LIÊN TỤC]
Matplotlib là một thư viện hỗ trợ vẽ đồ thị rất mạnh mẽ trong Python, có tính năng và cách sử dụng tương tự như trong Matlab.
CÀI ĐẶT
pip install matplotlib
VẼ ĐỒ THỊ VỚI CÁC TÙY CHỈNH MẶC ĐỊNH
Matplotlib đi kèm với các cài đặt mặc định, cho phép chúng ta tùy chỉnh tất cả các thuộc tính. Chúng ta có thể kiểm soát các giá trị mặc định của hầu hết các thuộc tính của matplotlib, bao gồm: figure size và dpi, line width, color và style, axes, axis và grid properties, text và font properties,…
Example 1: Plotting with default settings.
import numpy as np import matplotlib.pyplot as plt X = np.linspace(-np.pi, np.pi, 256, endpoint=True) C, S = np.cos(X), np.sin(X) plt.plot(X, C) plt.plot(X, S) plt.show()
Output:
KHỞI TẠO MẶC ĐỊNH
Những cài đặt này được chỉnh ở mặc định, hãy vọc vạch để tìm hiểu chúng nào.
Example 2: Instantiating defaults
import numpy as np import matplotlib.pyplot as plt # Create a figure of size 8x6 inches, 80 dots per inch plt.figure(figsize=(8, 6), dpi=80) # Create a new subplot from a grid of 1 row x 1 column plt.subplot(1, 1, 1) X = np.linspace(-np.pi, np.pi, 256, endpoint=True) C, S = np.cos(X), np.sin(X) # Plot cosine with a blue continuous line of width 1 (pixels) plt.plot(X, C, color="blue", linewidth=1.0, linestyle="-") # Plot sine with a green continuous line of width 1 (pixels) plt.plot(X, S, color="green", linewidth=1.0, linestyle="-") # Set x limits plt.xlim(-4.0, 4.0) # Set x ticks plt.xticks(np.linspace(-4, 4, 9, endpoint=True)) # Set y limits plt.ylim(-1.0, 1.0) # Set y ticks plt.yticks(np.linspace(-1, 1, 5, endpoint=True)) # Save figure using 72 dots per inch plt.savefig("example-2.png", dpi=72) # Show result on screen plt.show()
Output:
VẼ BIỂU ĐỒ ĐƯỜNG
Function:
Line2DList = pyplot.plot(X, Y, **kwargs)
Trong đó:
- X, Y – các tọa độ theo trục x và y;
- Line2DList – một List chứa các instance của class Line2D.
Function pyplot.plot() còn có các tham số cơ bản sau:
- color = [ ‘b’ | ‘g’ | ‘r’ | ‘c’ | ‘m’ | ‘y’ | ‘k’ | ‘w’ ];
- linewidth = float value in points;
- linestyle = [ ‘-‘ | ‘- -‘ | ‘-.’ | ‘:’ | ‘None’ ];
- marker = [ ‘.’ | ‘,’ | ‘o’ | ‘+’ | ‘x’ ], tham khảo [8];
- markersize = float value in points;
- label = String;
Các tham số color, marker, linestyple có thể được biễu diễn ở dạng ‘[color][marker][linestyle]‘, ví dụ: ‘ro-‘ tương đương với color=’r’, marker=’o’, linestyle=’-‘.
Example 3:
import numpy as np import matplotlib.pyplot as plt # Create a figure of size 8x6 inches, 80 dots per inch plt.figure(figsize=(8, 6), dpi=80) # Create a new subplot from a grid of 1x1 plt.subplot(1, 1, 1) X = np.linspace(-np.pi, np.pi, 32, endpoint=True) C = np.cos(X) # Plot cosine with a blue continuous line of width 1 (pixels) plt.plot(X, C, color='r', linestyle='--', linewidth=0.5, marker='o') plt.show()
Output:
THÊM LABEL VÀ TITLE
pyplot.xlabel(label)
pyplot.ylabel(label)
pyplot.title(title)
CÀI ĐẶT GIỚI HẠN CHO CÁC TRỤC
pyplot.xlim(xmin, xmax)
pyplot.ylim(ymin, ymax)
hoặc
pyplot.axis(xmin, xmax, ymin, ymax)
SETTING TICKS & TICK LABELS
pyplot.xticks([ticks], [tickLabels])
pyplot.yticks([ticks], [tickLabels])
Example 4: Setting ticks and tick labels
import numpy as np import matplotlib.pyplot as plt # Create a figure of size 8x6 inches, 80 dots per inch plt.figure(figsize=(8, 6), dpi=80) # Create a new subplot from a grid of 1x1 plt.subplot(1, 1, 1) X = np.linspace(-np.pi, np.pi, 32, endpoint=True) C = np.cos(X) # Plot cosine with a blue continuous line of width 1 (pixels) plt.plot(X, C, color='r', linestyle='--', linewidth=0.5, marker='o') plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) plt.yticks([-1, 0, +1], [r'$-1$', r'$0$', r'$+1$']) plt.show()
Output:
CHÚ THÍCH CHO ĐỒ THỊ
pyplot.plot(…, label=”y=cos(x)”)
pyplot.legend(loc=’upper right’)
Trong đó: loc là vị trí đặt chú thích, loc=
- ‘best’ hoặc 0
- ‘upper right’ hoặc 1
- ‘upper left’ hoặc 2
- ‘lower left’ hoặc 3
- ‘lower right’ hoặc 4
- ‘right’ hoặc 5
- ‘center left’ hoặc 6
- ‘center right’ hoặc 7
- ‘lower center’ hoặc 8
- ‘upper center’ hoặc 9
- ‘center’ hoặc 10
FIGURES
The top level container for all the plot elements. A figure is the windows in the GUI that has “Figure #” as title. Figures are numbered starting from 1 as opposed to the normal Python way starting from 0.
+ Tạo một Figure mới:
FigureInstance = pyplot.figure(num=1, figsize=figure.figsize, dpi=figure.dpi)
Trong đó:
- num: int or string – số thứ tự của figure, mặc định là 1, hoặc title của figure;
- figsize: tuple – figure size in in inches (width, height);
- dpi: int – resolution in dots per inch;
- FigureInstance – một instance của class Figure.
+ Đóng một Figure
pyplot.close(*args)
Trong đó:
- close(): đóng figure hiện tại;
- close(num): đóng figure có number là num;
- close(name): đóng figure có title là name;
- close(‘all’): đóng tất cả figure.
Example 5: Figure
import matplotlib.pyplot as plt import numpy as np X = np.linspace(0, 2*np.pi, 32, endpoint=True) S = np.sin(X) C = np.cos(X) figure1 = plt.figure("y = sin(x)") plt.plot(X,S) figure2 = plt.figure("y = cos(x)") plt.plot(X,C) plt.show(figure1) plt.show(figure2)
Output:
SUBPLOTS
With subplot you can arrange plots in a regular grid. You need to specify the number of rows and columns and the number of the plot. Note that the gridspec command is a more powerful alternative.
Function:
SubplotBaseInstance = pyplot.subplot(numberOfRow, numerOfColumn, position)
Trong đó:
- numberOfRow – số lượng subplot theo chiều dọc của figure;
- numberOfColumn – số lượng subplot theo chiều ngang của figure;
- position – vị trí của subplot cần tạo;
- SubplotBaseInstance – instance của class SubplotBase (là một subclass của class Axes).
Example 6: subplot
import numpy as np import matplotlib.pyplot as plt X = np.linspace(0, 2*np.pi, 32, endpoint=True) C = np.cos(X) S = np.sin(X) # Create a figure of size 8x6 inches, 80 dots per inch plt.figure("SinCos", figsize=(8, 6), dpi=80) # Plot sine with a blue continuous line of width 1 (pixels) plt.subplot(2, 1, 1) plt.plot(X, S, color='b', linestyle='--', linewidth=0.5, marker='o', label="y=sin(x)") plt.xticks(np.linspace(0, 2*np.pi, 5, endpoint=True), [r'$0$', r'$\pi/2$', r'$\pi$', r'$3\pi/2$', r'$2\pi$']) plt.yticks([-1, 0, +1], [r'$-1$', r'$0$', r'$+1$']) plt.legend(loc=0) # Plot cosine with a red continuous line of width 1 (pixels) plt.subplot(2, 1, 2) plt.plot(X, C, color='r', linestyle='--', linewidth=0.5, marker='o', label="y=cos(x)") plt.xticks(np.linspace(0, 2*np.pi, 5, endpoint=True), [r'$0$', r'$\pi/2$', r'$\pi$', r'$3\pi/2$', r'$2\pi$']) plt.yticks([-1, 0, +1], [r'$-1$', r'$0$', r'$+1$']) plt.legend(loc=0) plt.show()
Output:
AXES
Axes are very similar to subplots but allow placement of plots at any location in the figure. So if we want to put a smaller plot inside a bigger one we do so with axes.
Function:
AxesInstance = pyplot.axes([left, bottom, width, height])
Trong đó:
- left – tỉ lệ giữa khoảng cách đến cạnh trái của Figure và chiều rộng của Figure, thuộc khoảng [0, 1];
- bottom – tỉ lệ giữa khoảng cách đến đáy của Figure và chiều cao của Figure, thuộc khoảng [0, 1];
- width, height – các kích thước của axe so với Figure, thuộc khoảng [0, 1];
- AxesInstance – instance của class Axes.
Example 7: Axes
import matplotlib.pyplot as plt import numpy as np X = np.linspace(0, 2*np.pi, 32, endpoint=True) C, S = np.cos(X), np.sin(X) plt.axes([.1, .1, 0.8, 0.8]) plt.text(5, 0.9, 'y=sin(x)', ha='center', va='center', size=20, alpha=0.5) plt.xticks(()) plt.yticks(()) plt.plot(X, S, color='r', linestyle='--', linewidth=0.5, marker='o') plt.axes([.15, .15, .3, .3]) plt.text(3, 0.7, 'y=cos(x)', ha='center', va='center', size=10, alpha=0.5) plt.xticks(()) plt.yticks(()) plt.plot(X, C, color='b', linestyle='--', linewidth=0.5, marker='+') plt.show()
Output:
VẼ BIỂU ĐỒ SCATTER
Function pyplot.scatter() được sử dụng để vẽ biểu đồ scatter, với các tham số cơ bản sau:
- s – marker size, scalar hoặc array có số phần tử tương đương với số điểm trên đồ thị;
- c – marler color = [ ‘b’ | ‘g’ | ‘r’ | ‘c’ | ‘m’ | ‘y’ | ‘k’ | ‘w’ ];
- marker – tương tự với pyplot.plot(), xem thêm [8];
- alpha – độ mờ đục, trong khoảng [0.0, 1.0].
Example:
import numpy as np import matplotlib.pyplot as plt n = 100 X = np.random.randint(0,100, size=(n,)) Y = np.random.randint(0,100, size=(n,)) sizes = np.random.randint(10,50,size=(n,)) plt.scatter(X,Y, s=sizes, c='r', marker='D', alpha=0.25) plt.show()
Output:
VẼ BIỂU ĐỒ 3D
Để vẽ biểu đồ 3D chúng ta sẽ sử dụng bộ toolkit mpl_toolkits.mplot3d của matplotlib.
+ Tạo một subplot để vẽ biểu đồ 3D:
plot3d = pyplot.subplot(rows, columns, index, projection=’3d’)
Trong đó:
- rows, columns, index – số hàng, số cột và vị trí của subplot được tạo;
- projection=’3d’ – vẽ ở không gian 3 chiều;
- plot3d – Axes3DSubplot object, được sử dụng để vẽ biểu đồ 3D.
+ Vẽ biểu đồ đường 3D (các tham số tương tự với pyplot.plot):
plot3d.plot(X, Y, Z)
+ Vẽ biểu đồ mặt:
plot3d.plot_surface(X, Y, Z, cmap)
+ Vẽ biểu đồ scatter 3D (các tham số tương tự với pyplot.scatter):
plot3d.scatter(X, Y, Z, s, c)
+ Vẽ contour:
plot3d.contour(X, Y, Z, cmap, offset)
Trong đó:
- X, Y, Z – tọa độ trên các trục;
- cmap – tham khảo colarmaps, một số giá trị cmap: pyplot.cm.viridis, pyplot.cm.plasma, pyplot.cm.inferno, pyplot.cm.magma, pyplot.cm.cividis,…
Example:
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D plot3d = plt.subplot(111, projection='3d') X = np.arange(-4, 4, 0.25) Y = np.arange(-4, 4, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X ** 2 + Y ** 2) Z = np.sin(R) plot3d.set_zlim(-2, 2) plot3d.plot_surface(X, Y, Z, cmap=plt.cm.inferno) plot3d.contourf(X, Y, Z, offset=-2, cmap=plt.cm.inferno) plt.show()
Giải thích:
– Dòng 3: import Axes3D từ bộ toolkits mplot3d để có thể sử dụng keyword “projection”;
– Dòng 9: tạo ma trận lưới từ các tọa độ X và Y;
– Dòng 13: giới hạn kích thước theo trục Z;
– Dòng 14, 15: vẽ surface và contour tương ứng.
Output:
CẬP NHẬT ĐỒ THỊ
- ỨNG DỤNG #1: ĐỒ THỊ THEO DÕI HOẠT ĐỘNG
Để cập nhật đồ thị theo thời gian thực, chúng ta cần bật chế độ interactive của matplotlib với function pyplot.ion().
Example:
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10*np.pi, 100) y = np.sin(x) plt.ion() fig = plt.figure() ax = plt.subplot(111) line = ax.plot(x, y, 'b-')[0] for phase in np.linspace(0, 10*np.pi, 100): line.set_ydata(np.sin(0.5 * x + phase)) fig.canvas.draw_idle() fig.canvas.flush_events()
- ỨNG DỤNG #2:
Reference:
[1] Matplotlib.pyplot
[2] Matplotlib.figure
[3] Pyplot tutorial.
[4] Matplotlib: plotting.
[5] Matplotlib Tutorial: Python Plotting.
[6] Stackoverflow: How to update a plot in matplotlib?
[7] matplotlib.backend_bases.FigureCanvasBase
[8] matplotlib markers
One thought on “Matplotlib reference”