Matplotlib 箱线图:显示整数离群值的出现次数
Matplotlib Boxplot: Showing Number of Occurrences of Integer Outliers
我有如下图(使用 plt.boxplot()
):
现在,我想要绘制一个数字,这些异常值出现的频率(最好在每个异常值的右上角)。
这是否可以实现?
ax.boxplot
returns 箱线图中所有元素的字典。你需要的那个字典的关键是 'fliers'
.
在boxdict['fliers']
中,有Line2D
个实例用于绘制传单。我们可以使用 .get_xdata()
和 .get_ydata()
获取他们的 x
和 y
位置。
您可以使用 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()
我有如下图(使用 plt.boxplot()
):
现在,我想要绘制一个数字,这些异常值出现的频率(最好在每个异常值的右上角)。
这是否可以实现?
ax.boxplot
returns 箱线图中所有元素的字典。你需要的那个字典的关键是 'fliers'
.
在boxdict['fliers']
中,有Line2D
个实例用于绘制传单。我们可以使用 .get_xdata()
和 .get_ydata()
获取他们的 x
和 y
位置。
您可以使用 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()