In [1]:
from matplotlib import pyplot as plt
import numpy as np
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 中文字體支持
1 餅圖-pie()¶
1.1 pie()方法參數說明¶
pie()是matplotlib中畫餅圖的方法,其主要參數如下:
1.2 基礎作圖¶
In [3]:
labels = 'Python組', 'Java組', 'C組', 'Go組'
sizes = [25, 45, 30, 10]
fig = plt.figure(figsize=(8, 4))
ax1 = fig.add_subplot(111)
ax1.pie(sizes, labels=labels)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()
1.3 字符標簽與數值標簽¶
In [4]:
labels = 'Python組', 'Java組', 'C組', 'Go組'
sizes = [25, 45, 30, 10]
fig = plt.figure(figsize=(8, 4))
ax1 = fig.add_subplot(121)
ax1.pie(sizes,
labels=labels, # 字符標簽
labeldistance=1.1, # 字符標簽到中心點的距離
autopct='%1.1f%%', # 顯示數值標簽
pctdistance=0.5 #數值標簽到中心點的距離
)
ax2 = fig.add_subplot(122)
ax2.pie(sizes,
labels=labels, # 字符標簽
labeldistance=0.4, # 字符標簽到中心點的距離
autopct='%1.2f%%', # 顯示數值標簽
pctdistance=1.2, #數值標簽到中心點的距離
rotatelabels=True # 旋轉標簽
)
plt.show()
1.4 扇形分隔距離¶
In [5]:
labels = 'Python組', 'Java組', 'C組', 'Go組'
sizes = [25, 45, 30, 10]
fig = plt.figure(figsize=(8, 4))
explode1 = (0.1, 0.1, 0.1, 0.1)
ax1 = fig.add_subplot(121)
ax1.pie(sizes, explode=explode1, # 分隔扇形
labels=labels, autopct='%1.1f%%')
explode2 = (0.1, 0, 0, 0)
ax2 = fig.add_subplot(122)
ax2.pie(sizes, explode=explode2, # 分隔扇形
labels=labels, autopct='%1.1f%%')
plt.show()
1.5 陰影與邊框¶
In [6]:
labels = 'Python組', 'Java組', 'C組', 'Go組'
sizes = [25, 45, 30, 10]
explode = (0.1, 0, 0, 0)
fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, # 顯示陰影
wedgeprops = {'linewidth': 3} # 設置邊框寬度
)
plt.show()
1.6 旋轉圖形¶
In [7]:
labels = 'Python組', 'Java組', 'C組', 'Go組'
sizes = [25, 45, 30, 10]
explode = (0.1, 0, 0, 0)
fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True,
startangle=90 # 旋轉
)
plt.show()
1.7 單獨設置某一扇形¶
pie()方法返回一個tuple,第一個元素為每個扇形對象組成的list,第二個元素為每個扇形的標簽Text對象,第三個元素為每個扇形的數值標簽對象,通過這三個對象,可以實現對單一扇形的設置。
In [8]:
labels = 'Python組', 'Java組', 'C組', 'Go組'
sizes = [25, 45, 30, 10]
explode = (0.1, 0, 0, 0)
fig1, ax1 = plt.subplots()
patches, texts, autotexts = ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%')
print('第1個返回值:',patches)
print('第2個返回值:',texts)
print('第3個返回值:',autotexts)
texts[0].set_color('red') # 設置第一個扇形的字符標簽字體顏色
texts[0].set_fontsize(30) # 設置第一個扇形的字符標簽字體大小
autotexts[0].set_color('white') # 設置第一個扇形的數值標簽字體顏色
plt.show()
第1個返回值: [<matplotlib.patches.Wedge object at 0x7efe1de27450>, <matplotlib.patches.Wedge object at 0x7efe1de27a50>, <matplotlib.patches.Wedge object at 0x7efe1de311d0>, <matplotlib.patches.Wedge object at 0x7efe1de31a90>] 第2個返回值: [Text(0.9068994725035225, 0.7858329000320824, 'Python組'), Text(-1.0005952104475537, 0.4569564802357176, 'Java組'), Text(0.15654637770487598, -1.0888035780743386, 'C組'), Text(1.055442297353649, -0.30990572269135586, 'Go組')] 第3個返回值: [Text(0.5290246922937214, 0.4584025250187147, '22.7%'), Text(-0.5457792056986657, 0.2492489892194823, '40.9%'), Text(0.0853889332935687, -0.593892860767821, '27.3%'), Text(0.5756957985565357, -0.1690394851043759, '9.1%')]
In [9]:
labels = 'Python組', 'Java組', 'C組', 'Go組'
sizes = [25, 45, 30, 10]
explode = (0.1, 0, 0, 0)
fig1, ax1 = plt.subplots(figsize=(5, 5))
patches, texts, autotexts = ax1.pie(sizes, explode=explode, autopct='%1.1f%%')
ax1.legend(patches, labels, loc="upper right",bbox_to_anchor=(0.75, 0, 0.5, 0.4))
plt.show()
1.8 嵌套餅圖¶
In [10]:
sizes = {
'Python組':{'男':10, '女': 15},
'Java組':{'男':15, '女': 30},
'C組':{'男':5, '女': 25},
'Go組':{'男':4, '女': 6}
}
def func(sizes):
"""提取數據和標簽"""
data1 = []
data2 = []
data2_label = []
for key in sizes.keys():
data1.append(sizes.get(key).get('男') + sizes.get(key).get('女'))
data2.append(sizes.get(key).get('男'))
data2_label.append(key+'-'+'男')
data2.append(sizes.get(key).get('女'))
data2_label.append(key+'-'+'女')
return data1, data2, sizes.keys(), data2_label
data1, data2, data1_label, data2_label = func(sizes)
cmap = plt.get_cmap("tab20c")
outer_colors = cmap(np.arange(4)*4)
inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10, 13, 14]))
fig = plt.figure(figsize=(10, 4))
ax1 = fig.add_subplot(121)
ax1.pie(data1, labels=data1_label, radius=1.5, colors=outer_colors, autopct='%1.1f%%', labeldistance=1, pctdistance=0.8)
ax1.pie(data2, labels=data2_label, radius=1, colors=inner_colors, autopct='%1.1f%%', labeldistance=0.4, pctdistance=0.9)
ax2 = fig.add_subplot(122)
ax2.pie(data1, labels=data1_label, radius=1.5, colors=outer_colors, autopct='%1.1f%%', labeldistance=1, pctdistance=0.8,wedgeprops=dict(width=0.8, edgecolor='w'))
ax2.pie(data2, labels=data2_label, radius=1, colors=inner_colors, autopct='%1.1f%%', labeldistance=0.4, pctdistance=0.9,wedgeprops=dict(width=0.6, edgecolor='w'))
plt.show()
2 箱線圖¶
2.1 參數說明¶
matplotlib繪制箱線圖通過boxplot()方法實現,主要參數如下:
boxplot()方法返回值是一個dict,鍵值包括'whiskers'、'caps'、'boxes'、'fliers'、'means',分別表示須線、頂端末端線段、箱體、異常數據、均值等繪圖對象分別組成的列表,通過這些對象可以橫放把您的實現箱線圖各個部分的自定義設置。
2.2 基礎作圖¶
In [11]:
data=np.random.normal(0,4,100)
fig = plt.figure(figsize=(8, 8))
ax1 = fig.add_subplot(221)
ax1.set_title('圖1 常規作圖')
ax1.boxplot(data)
muti_data=[np.random.normal(0,std,100) for std in range(1,4)]
ax2 = fig.add_subplot(222)
ax2.set_title('圖2 多圖繪制')
ax2.boxplot(muti_data)
ax3 = fig.add_subplot(223)
ax3.set_title('圖3 水平箱線圖')
ax3.boxplot(data, vert=False)
ax4 = fig.add_subplot(224)
ax4.set_title('圖4 中間凹陷')
ax4.boxplot(data, notch=True)
plt.show()
2.3 修改標簽¶
In [12]:
data=np.random.normal(0,4,100)
fig = plt.figure(figsize=(8, 4))
muti_data=[np.random.normal(0,std,100) for std in range(1,4)]
ax2 = fig.add_subplot(121)
ax2.set_title('圖1')
ax2.boxplot(muti_data, labels=['第1組', '第2組', '第3組'])
muti_data=[np.random.normal(0,std,100) for std in range(1,4)]
ax2 = fig.add_subplot(122)
ax2.set_title('圖2')
ax2.boxplot(muti_data, vert=False, labels=['第1組', '第2組', '第3組'])
plt.show()
2.4 顯示均值¶
In [13]:
data=np.random.normal(0,4,100)
fig = plt.figure(figsize=(8, 4))
muti_data=[np.random.normal(0,std,100) for std in range(1,4)]
ax2 = fig.add_subplot(121)
ax2.set_title('圖1')
ax2.boxplot(muti_data, labels=['第1組', '第2組', '第3組'], showmeans=True) # 顯示均值,默認以點的方式顯示
muti_data=[np.random.normal(0,std,100) for std in range(1,4)]
ax2 = fig.add_subplot(122)
ax2.set_title('圖2')
ax2.boxplot(muti_data, labels=['第1組', '第2組', '第3組'], showmeans=True, meanline=True) # 顯示均值,並以橫線方式顯示
plt.show()
2.5 箱體設置¶
In [14]:
data=np.random.normal(0,4,100)
fig = plt.figure(figsize=(8, 4))
muti_data=[np.random.normal(0,std,100) for std in range(1,4)]
ax2 = fig.add_subplot(121)
ax2.set_title('圖1')
box_dict = ax2.boxplot(muti_data, labels=['第1組', '第2組', '第3組'], patch_artist=True) # 注意,patch_artist一定要設置為True,下面的設置才會生效
box_dict.get('boxes')[0].set_color('red') # 箱體邊框顏色
box_dict.get('boxes')[1].set_color('blue')
box_dict.get('boxes')[2].set_color('green')
plt.show()
