Phần 17: Pie Chart ( Biểu đồ tròn ) – Matplotib Basic

1. Khái niệm chung :
Biểu đồ tròn có thể hiển thị 1 chuỗi dữ liệu. Biểu đồ tròn hiển thị kích thước của những mục (được gọi là wedge) trong 1 chuỗi dữ liệu, tỷ lệ với tổng của những mục. Các điểm dữ liệu trong biểu đồ tròn được hiển thị dưới dạng phần trăm của tất cả hình tròn.
Matplotlib API có 1 hàm pie () tạo nên 1 biểu đồ tròn đại diện cho dữ liệu trong 1 mảng. Diện tích phần của mỗi hình wedge được cho do x / sum (x). Nếu như sum (x)
Biểu đồ hình tròn nhìn đẹp nhất nếu như hình và trục là hình vuông hay góc cạnh Axes bằng nhau.
Các tham số cần phải biết :
x | giống mảng. Các kích thước wedge. |
---|---|
labels | danh sách. 1 chuỗi các chuỗi cung cấp các label cho mỗi wedge. |
Colors | 1 chuỗi các vòng màu matplotlib mà qua đó biểu đồ tròn sẽ xoay vòng. Nếu như Không, sẽ sử dụng các màu trong chu kỳ hiện đang chạy. |
Autopct | chuỗi, được dùng để gắn label các wedge với giá trị số . Label sẽ được đặt bên trong wedge. Chuỗi định dạng sẽ là fmt% pct. |
Đoạn mã sau sử dụng hàm pie () để hiển thị biểu đồ tròn của danh sách sinh viên đăng ký các khóa học ngôn ngữ máy tính khác nhau. Tỷ lệ phần trăm tương ứng được hiển thị bên trong nêm ứng với sự giúp đỡ của tham số autopct được đặt thành% 1.2f%.
from matplotlib import pyplot as plt
import numpy as np
fig = plt.determine()
ax = fig.add_axes([0,0,1,1])
ax.axis('equal')
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
college students = [23,17,35,29,12]
ax.pie(college students, labels = langs,autopct='%1.2f%%')
plt.present()
2. Ví dụ minh hoạ :
Ví dụ 1 : Demo của biểu đồ tròn trên 1 trục cực.
import numpy as np
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)
# Compute pie slices
N = 20
theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False)
radii = 10 * np.random.rand(N)
width = np.pi / 4 * np.random.rand(N)
colours = plt.cm.viridis(radii / 10.)
ax = plt.subplot(111, projection='polar')
ax.bar(theta, radii, width=width, backside=0.0, coloration=colours, alpha=0.5)
plt.present()
Kết quả :
Ví dụ 2 : Bar of pie
Tạo biểu đồ “Bar of pie” trong đó lát đầu tiên của hình tròn được “exploded” thành biểu đồ thanh với sự phân tích sâu hơn về các đặc điểm của lát đó. Ví dụ minh họa bằng việc dùng 1 hình có nhiều bộ trục và sử dụng danh sách những bản vá trục để thêm 2 Bản vá kết nối để liên kết các biểu đồ subplot.
import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch
import numpy as np
# make determine and assign axis objects
fig = plt.determine(figsize=(9, 5.0625))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
fig.subplots_adjust(wspace=0)
# pie chart parameters
ratios = [.27, .56, .17]
labels = ['Approve', 'Disapprove', 'Undecided']
explode = [0.1, 0, 0]
# rotate in order that first wedge is cut up by the x-axis
angle = -180 * ratios[0]
ax1.pie(ratios, autopct='%1.1f%%', startangle=angle,
labels=labels, explode=explode)
# bar chart parameters
xpos = 0
backside = 0
ratios = [.33, .54, .07, .06]
width = .2
colours = [[.1, .3, .5], [.1, .3, .3], [.1, .3, .7], [.1, .3, .9]]
for j in vary(len(ratios)):
peak = ratios[j]
ax2.bar(xpos, peak, width, backside=backside, coloration=colours[j])
ypos = backside + ax2.patches[j].get_height() / 2
backside += peak
ax2.textual content(xpos, ypos, "%d%%" % (ax2.patches[j].get_height() * 100),
ha='heart')
ax2.set_title('Age of approvers')
ax2.legend(('50-65', 'Over 65', '35-49', 'Under 35'))
ax2.axis('off')
ax2.set_xlim(- 2.5 * width, 2.5 * width)
# use ConnectionPatch to attract strains between the 2 plots
# get the wedge information
theta1, theta2 = ax1.patches[0].theta1, ax1.patches[0].theta2
heart, r = ax1.patches[0].heart, ax1.patches[0].r
bar_height = sum([item.get_height() for item in ax2.patches])
# draw high connecting line
x = r * np.cos(np.pi / 180 * theta2) + heart[0]
y = np.sin(np.pi / 180 * theta2) + heart[1]
con = ConnectionPatch(xyA=(- width / 2, bar_height), xyB=(x, y),
coordsA="information", coordsB="information", axesA=ax2, axesB=ax1)
con.set_color([0, 0, 0])
con.set_linewidth(4)
ax2.add_artist(con)
# draw backside connecting line
x = r * np.cos(np.pi / 180 * theta1) + heart[0]
y = np.sin(np.pi / 180 * theta1) + heart[1]
con = ConnectionPatch(xyA=(- width / 2, 0), xyB=(x, y), coordsA="information",
coordsB="information", axesA=ax2, axesB=ax1)
con.set_color([0, 0, 0])
ax2.add_artist(con)
con.set_linewidth(4)
plt.present()
Ví dụ 3 :
import matplotlib.pyplot as plt
# Pie chart, the place the slices can be ordered and plotted counter-clockwise:
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0) # solely "explode" the 2nd slice (i.e. 'Hogs')
fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90)
ax1.axis('equal') # Equal facet ratio ensures that pie is drawn as a circle.
plt.present()