In [1]:
%matplotlib inline
np.random.normal()的意思是一個正態分布:numpy.random.normal(loc=0,scale=1e-2,size=shape)
- 參數loc(float):正態分布的均值,對應着這個分布的中心。loc=0說明這一個以Y軸為對稱軸的正態分布,
- 參數scale(float):正態分布的標准差,對應分布的寬度,scale越大,正態分布的曲線越矮胖,scale越小,曲線越高瘦。
- 參數size(int 或者整數元組):輸出的值賦在shape里,默認為None。
-
boxplot(sym = 'o', #異常點形狀
vert = True, # 是否垂直
whis=1.5, # IQR
patch_artist = True, # 上下四分位框是否填充
meanline = False,showmeans = True, # 是否有均值線及其形狀
showbox = True, # 是否顯示箱線
showfliers = True, #是否顯示異常值
notch = False, # 中間箱體是否缺口
return_type='dict') # 返回類型為字典
In [2]:
import matplotlib.pyplot as plt
import numpy as np
tang_data=[np.random.normal(0,std,100) for std in range(1,4)]
fig=plt.figure(figsize=(8,6))
plt.boxplot(tang_data,notch=False,sym='s',vert=True)
plt.xticks([y+1 for y in range(len(tang_data))],['x1','x2','x3'])
plt.xlabel('x')
plt.title('boxplot')
Out[2]:
2.設置黑白的的箱型圖
In [3]:
tang_data=[np.random.normal(0,std,100) for std in range(1,4)]
fig=plt.figure(figsize=(8,6))
bplot=plt.boxplot(tang_data,notch=False,sym='s',vert=True)
plt.xticks([y+1 for y in range(len(tang_data))],['x1','x2','x3'])
plt.xlabel('x')
plt.title('boxplot')
#設置每個線條顏色
for components in bplot.keys():
for line in bplot[components]:
line.set_color('black')
3.畫橫的箱型圖:修改參數vert=False
In [4]:
tang_data=[np.random.normal(0,std,100) for std in range(1,4)]
fig=plt.figure(figsize=(8,6))
bplot=plt.boxplot(tang_data,notch=False,sym='s',vert=False)
plt.yticks([y+1 for y in range(len(tang_data))],['x1','x2','x3'])
plt.ylabel('x')
plt.title('boxplot')
Out[4]:
4.notch = False #中間箱體是否缺口
In [5]:
tang_data=[np.random.normal(0,std,100) for std in range(1,4)]
fig=plt.figure(figsize=(8,6))
bplot=plt.boxplot(tang_data,notch=True,sym='s',vert=False)
plt.yticks([y+1 for y in range(len(tang_data))],['x1','x2','x3'])
plt.ylabel('x')
plt.title('boxplot')
Out[5]:
5.填充顏色:添加屬性設置patch_artist=True,設置顏色 pathch.set_facecolor(color)
In [6]:
tang_data=[np.random.normal(0,std,100) for std in range(1,4)]
fig=plt.figure(figsize=(8,6))
bplot=plt.boxplot(tang_data,notch=False,sym='s',vert=False,patch_artist=True)#patch_artist=True上下四分位框是否填充
plt.yticks([y+1 for y in range(len(tang_data))],['x1','x2','x3'])
plt.ylabel('x')
plt.title('boxplot')
#填充顏色
colors=['pink','lightblue','lightgreen']#顏色定義
for pathch,color in zip(bplot['boxes'],colors):
pathch.set_facecolor(color)#設置顏色
小提琴圖 violinplot¶
In [7]:
fig,axes=plt.subplots(nrows=1,ncols=2,figsize=(12,5))#設置小提琴圖1行2列
tang_data=[np.random.normal(0,std,100)for std in range (6,10)]#設置數據
axes[0].violinplot(tang_data,showmeans=False,showmedians=True)#畫小提琴圖
axes[0].set_title('violin plot')
axes[1].boxplot(tang_data)#畫箱型圖
axes[1].set_title('box_plot')
#grid畫橫線
for ax in axes:
ax.yaxis.grid(True)
ax.set_xticks([y+1 for y in range(len(tang_data))])
#標注X軸lable
plt.setp(axes,xticks=[y+1 for y in range(len(tang_data))],xticklabels=['x1','x2','x3','x4'])
Out[7]: