python 使用 matplotlib.pyplot來畫柱狀圖和餅圖
阿新 • • 發佈:2018-11-16
匯入包
import matplotlib.pyplot as plt
柱狀圖
最簡柱狀圖
# 顯示高度 def autolabel(rects): for rect in rects: height = rect.get_height() plt.text(rect.get_x()+rect.get_width()/2.- 0.2, 1.03*height, '%s' % int(height)) name_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] num_list = [33, 44, 53, 16, 11, 17, 17, 10] autolabel(plt.bar(range(len(num_list)), num_list, color='rgb', tick_label=name_list)) plt.show()
結果
堆疊柱狀圖
# 顯示高度 def autolabel(rects1, rects2): i = 0 for rect1 in rects1: rect2 = rects2[i] i += 1 height = rect1.get_height() + rect2.get_height() plt.text(rect1.get_x()+rect1.get_width()/2. - 0.1, 1.03*height, '%s' % int(height)) name_list = ['A', 'B', 'C', 'D'] num_list = [10, 15, 16, 28] num_list2 = [10, 12, 18, 26] z1 = plt.bar(range(len(num_list)), num_list, label='1', fc='b') z2 = plt.bar(range(len(num_list)), num_list2, bottom=num_list, label='2', tick_label=name_list, fc='g') autolabel(z1, z2) plt.legend() plt.show()
結果
並列柱狀圖
name_list = ['A', 'B', 'C', 'D'] num_list = [10, 15, 16, 28] num_list2 = [10, 12, 18, 26] x = list(range(len(num_list))) total_width, n = 0.8, 2 width = total_width / n plt.bar(x, num_list, width=width, label='1', fc='b') for i in range(len(x)): x[i] += width plt.bar(x, num_list2, width=width, label='2', tick_label=name_list, fc='g') plt.legend() plt.show()
結果
餅圖
最簡餅圖
name_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
num_list = [33, 44, 53, 6,11, 7, 7, 10, 3, 1]
# 保證圓形
plt.axes(aspect=1)
plt.pie(x=num_list, labels=name_list, autopct='%3.1f %%')
plt.show()
結果
帶切割的餅圖
# 圓形
plt.figure(1, figsize=(6, 6))
name_list = ['A', 'B', 'C', 'D', 'E']
num_list = [33, 44, 53, 30, 60]
expl = [0, 0, 0, 0, 1]
colors = ['pink', 'blue', 'yellow', 'green', 'red']
plt.pie(x=num_list,explode=expl, labels=name_list, autopct='%3.1f %%', colors=colors, pctdistance=0.3, shadow=True)
plt.show()
結果