Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

python - Matplotlib Boxplot: Showing Number of Occurrences of Integer Outliers

I have a plot like the following (using plt.boxplot()): Boxplot with Integer Outliers

Now, what I want is plotting a number how often those outliers occured (preferably to the top right of each outlier).

Is that somehow achievable?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ax.boxplot returns a dictionary of all the elements in the boxplot. The key you need here from that dict is 'fliers'.

In boxdict['fliers'], there are the Line2D instances that are used to plot the fliers. We can grab their x and y locations using .get_xdata() and .get_ydata().

You can find all the unique y locations using a set, and then find the number of fliers plotted at that location using .count().

Then its just a case of using matplotlib's ax.text to add a text label to the plot.

Consider the following example:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...