Python 3.x Python:如何在框和须图中打印框、须和异常值?
我已经为我的数据绘制了一个方框和胡须图 我的代码:Python 3.x Python:如何在框和须图中打印框、须和异常值?,python-3.x,matplotlib,boxplot,Python 3.x,Matplotlib,Boxplot,我已经为我的数据绘制了一个方框和胡须图 我的代码: red_diamond = dict(markerfacecolor='r', marker='D') fig3, ax3 = plt.subplots() ax3.set_title('Changed Outlier Symbols') ax3.boxplot(maximum.values[:,1], flierprops=red_diamond) 我得到了一个图,如下所示: 我想做什么:在绘图本身上打印胡须、异常值(红色钻石)、四分位数
red_diamond = dict(markerfacecolor='r', marker='D')
fig3, ax3 = plt.subplots()
ax3.set_title('Changed Outlier Symbols')
ax3.boxplot(maximum.values[:,1], flierprops=red_diamond)
我得到了一个图,如下所示:
我想做什么:在绘图本身上打印胡须、异常值(红色钻石)、四分位数和中值的值 返回一个字典,其中包含在生成框和须图时绘制的所有行。一个选项是查询此词典,并根据其包含的信息创建标签。相关的关键是:
- IQR的
框
用于中间带中间带
胡须帽
- 异常值的
传单
import matplotlib.pyplot as plt
import numpy as np
# Make some dummy data
np.random.seed(1)
dummy_data = np.random.lognormal(size=40)
def make_labels(ax, boxplot):
# Grab the relevant Line2D instances from the boxplot dictionary
iqr = boxplot['boxes'][0]
caps = boxplot['caps']
med = boxplot['medians'][0]
fly = boxplot['fliers'][0]
# The x position of the median line
xpos = med.get_xdata()
# Lets make the text have a horizontal offset which is some
# fraction of the width of the box
xoff = 0.10 * (xpos[1] - xpos[0])
# The x position of the labels
xlabel = xpos[1] + xoff
# The median is the y-position of the median line
median = med.get_ydata()[1]
# The 25th and 75th percentiles are found from the
# top and bottom (max and min) of the box
pc25 = iqr.get_ydata().min()
pc75 = iqr.get_ydata().max()
# The caps give the vertical position of the ends of the whiskers
capbottom = caps[0].get_ydata()[0]
captop = caps[1].get_ydata()[0]
# Make some labels on the figure using the values derived above
ax.text(xlabel, median,
'Median = {:6.3g}'.format(median), va='center')
ax.text(xlabel, pc25,
'25th percentile = {:6.3g}'.format(pc25), va='center')
ax.text(xlabel, pc75,
'75th percentile = {:6.3g}'.format(pc75), va='center')
ax.text(xlabel, capbottom,
'Bottom cap = {:6.3g}'.format(capbottom), va='center')
ax.text(xlabel, captop,
'Top cap = {:6.3g}'.format(captop), va='center')
# Many fliers, so we loop over them and create a label for each one
for flier in fly.get_ydata():
ax.text(1 + xoff, flier,
'Flier = {:6.3g}'.format(flier), va='center')
# Make the figure
red_diamond = dict(markerfacecolor='r', marker='D')
fig3, ax3 = plt.subplots()
ax3.set_title('Changed Outlier Symbols')
# Create the boxplot and store the resulting python dictionary
my_boxes = ax3.boxplot(dummy_data, flierprops=red_diamond)
# Call the function to make labels
make_labels(ax3, my_boxes)
plt.show()
Hey@tmdavison,非常感谢您的回复。它起作用了。我有一个小要求和一个问题。我的要求:如果可能的话,你能给你的代码添加注释,这样我就能更好地理解它。我的问题是:使用这个之后,我得到了传单和价值观。但一个点周围有太多传单,文本会重叠。我试着缩小传单文本的字体大小,但它们变得非常小,无法阅读。有没有办法解决这个问题?谢意补充道。至于问题:这可能是更多的工作。简单的选择是每隔一个传单标签(例如,或每隔5个标签)打印一次。或者可以为每个标签指定不同的x偏移。或者,您可以通过某种方式进行搜索,查看是否已在某个阈值内标记某个点,如果已标记,则不打印该标签或移动该标签。确切地说,哪一个是最好的选择将取决于您的确切情节和首选外观,因此我认为您最好尝试其中一些选项。