2017-07-27 30 views

回答

2

ax.boxplot返回boxplot中所有元素的字典。這個詞典中你需要的關鍵是'fliers'

boxdict['fliers']中,有Line2D實例用於繪製飛行員。我們可以使用.get_xdata().get_ydata()來獲取他們的xy位置。

您可以使用set找到所有唯一y位置,然後使用.count()找到在該位置繪製的飛行員數量。

然後它只是一個使用matplotlib的ax.text添加文本標籤到情節的情況。

考慮下面的例子:

import matplotlib.pyplot as plt 
import numpy as np 

# Some fake data 
data = np.zeros((10000, 2)) 
data[0:4, 0] = 1 
data[4:6, 0] = 2 
data[6:10, 0] = 3 
data[0:9, 1] = 1 
data[9:14, 1] = 2 
data[14:20, 1] = 3 

# create figure and axes 
fig, ax = plt.subplots(1) 

# plot boxplot, grab dict 
boxdict = ax.boxplot(data) 

# the fliers from the dictionary 
fliers = boxdict['fliers'] 

# loop over boxes in x direction 
for j in range(len(fliers)): 

    # the y and x positions of the fliers 
    yfliers = boxdict['fliers'][j].get_ydata() 
    xfliers = boxdict['fliers'][j].get_xdata() 

    # the unique locations of fliers in y 
    ufliers = set(yfliers) 

    # loop over unique fliers 
    for i, uf in enumerate(ufliers): 

     # print number of fliers 
     ax.text(xfliers[i] + 0.03, uf + 0.03, list(yfliers).count(uf)) 

plt.show() 

enter image description here

相關問題