# dùng lệnh bên dưới để hiển thị inline trong Jupyter notebook
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
Figure là bounding box của biểu đồ mà ta trình bày. Một figure sẽ gồm 1 hay nhiều Axes.
# tạo một figure rỗng, không có axes nào
fig = plt.figure()
# đặt title cho figure
fig.suptitle("Không có Axes trong Figure này")
Text(0.5,0.98,'Không có Axes trong Figure này')
<Figure size 432x288 with 0 Axes>
# tạo một figure gồm 2x2 grid Axes
fig, ax_lst = plt.subplots(2, 2)
Đây là nơi bạn "plot" biểu đồ của mình, toàn bộ hình ảnh và thông tin sẽ được hiển thị tại đây. Một Figure có thể có nhiều Axes nhưng một Axes chỉ có thể đặt trong một Figure. Một Axes có thể có hai (hay ba, trong trường hợp không gian 3D) Axis (trục toạ độ) dùng giới hạn đoạn giá trị tương ứng (dùng hàm set_xlim()
, set_ylim()
). Mỗi Axes có title (dùng hàm set_title()
), x-label (dùng hàm set_xlabel()
), và y-label (dùng hàm set_ylabel()
).
Trục toạ độ dùng giới hạn miền giá trị và tạo các ticks (những dấu gạch dọc trên trục) và ticklabels (nhãn/giá trị bên dưới ticks). Vị trí của ticks được định nghĩa bởi Locator object, ticklabel được định dạng bởi Formatter.
Những gì ta thấy trên Figure đều là Artist (Figure, Axes, Axis, Text, Line2D, etc). Khi Figure được render, tất cả những artist này sẽ được vẽ lên canvas.
x_data = [1, 2, 3, 4]
y_data = [1, 4, 9, 16]
fig, ax = plt.subplots()
# line plot
ax.plot(x_data, y_data)
# artists
ax.set_xlabel('some numbers X')
ax.set_ylabel('some numbers Y')
ax.grid(True)
ax.set_title("Plotting example")
#
plt.show()
x_data = [1, 2, 3, 4]
y_data = [1, 4, 9, 16]
fig, ax = plt.subplots()
# line plot
ax.plot(x_data, y_data)
# artist
ax.set_xticks(x_data)
ax.set_xticklabels(["One", "Two", "Three", "Four"])
#
plt.show()
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
AutoMinorLocator)
# each major's step = 20
majorLocator = MultipleLocator(20)
# major's format is digit
majorFormatter = FormatStrFormatter('%d')
# minor's step = 5
minorLocator = MultipleLocator(5)
# create sample values
t = np.arange(0.0, 100.0, 0.1)
s = np.sin(0.1 * np.pi * t) * np.exp(-t * 0.01)
# plotting
fig, ax = plt.subplots()
# artist
ax.plot(t, s)
# major setup
ax.xaxis.set_major_locator(majorLocator)
ax.xaxis.set_major_formatter(majorFormatter)
# for the minor ticks, use no labels; default NullFormatter
ax.xaxis.set_minor_locator(minorLocator)
plt.show()
fmt = '[color][marker][line]'
Color
character | color |
---|---|
'b' | blue |
'g' | green |
'r' | red |
'c' | cyan |
'm' | magenta |
'y' | yellow |
'k' | black |
'w' | white |
Markers
character | description |
---|---|
'.' | 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 |
Lines
character | description |
---|---|
'-' | solid line style |
'--' | dashed line style |
'-.' | dash-dot line style |
':' | dotted line style |
fmt_string = "go-."
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], fmt_string)
plt.show()
# subplot 1: with indexing
names = ['group_a', 'group_b', 'group_c']
values = [1, 10, 100]
plt.figure(1, figsize=(9, 3))
# 131 is nrows=1, ncols=3, pos=1
plt.subplot(131)
plt.bar(names, values)
# 132 is nrows=1, ncols=3, pos=2
plt.subplot(132)
plt.scatter(names, values)
# 133 is nrows=1, ncols=3, pos=3
plt.subplot(133)
plt.plot(names, values)
plt.suptitle('Categorical Plotting')
plt.show()
# subplots 2: with 1D array (nrows=1) or 2D array (nrows > 1)
names = ['group_a', 'group_b', 'group_c']
values = [1, 10, 100]
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(9, 3))
axes[0].bar(names, values)
axes[1].scatter(names, values)
axes[2].plot(names, values)
plt.suptitle('Categorical Plotting')
plt.show()
# subplots 3: exploding into tuptle of axes
fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, figsize=(9, 3))
ax1.bar(names, values)
ax2.scatter(names, values)
ax3.plot(names, values)
plt.suptitle('Categorical Plotting')
plt.show()
Trong Matplotlib có rất nhiều styles khác nhau để bạn visualize theo ý thích. Để xem tất cả các style hỗ trợ hiện tại, ta có thể dùng pyplot.style.
ls_style = plt.style.available
print("Num: {}, List:{}".format(len(ls_style), ls_style))
Num: 26, List:['seaborn-talk', 'seaborn-deep', 'seaborn-darkgrid', 'seaborn-dark-palette', 'dark_background', 'seaborn-notebook', 'fast', 'seaborn-poster', '_classic_test', 'tableau-colorblind10', 'ggplot', 'seaborn-ticks', 'seaborn-paper', 'fivethirtyeight', 'seaborn-muted', 'seaborn-white', 'grayscale', 'bmh', 'seaborn-whitegrid', 'seaborn-colorblind', 'seaborn-bright', 'Solarize_Light2', 'classic', 'seaborn-pastel', 'seaborn', 'seaborn-dark']
# view all style examples
names = ['group_a', 'group_b', 'group_c']
values = [1, 10, 100]
for i in range(len(ls_style)):
st = ls_style[i]
plt.style.use(st)
plt.figure(figsize=(5, 5))
plt.bar(names, values)
plt.title(st)
plt.show()
Nguồn tham khảo: https://matplotlib.org/tutorials/index.html