Python:如何在方格图和晶须图中打印方格,晶须和离群值?

时间:2019-04-12 09:38:12

标签: 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)

,我得到了如下图: enter image description here

我要做什么:在图上打印晶须,离群值(红色菱形),四分位数和中位数的值。

1 个答案:

答案 0 :(得分:1)

ax.boxplot返回一个字典,其中包含在盒形图和晶须图中绘制的所有线条。一种选择是查询该词典,并根据其包含的信息创建标签。相关的键是:

  • boxes用于IQR
  • medians为中位数
  • caps用于晶须
  • fliers(离群值)

请注意,下面的功能仅对单个箱形图有效(如果您一次性创建了多个箱形,则需要更加谨慎地从字典中获取信息)。

一种替代方法是从数据数组本身中查找信息(找到中值和IQR很容易)。我不确定matplotlib如何确定传单是什么以及帽子应该放在哪里。如果要这样做,修改下面的功能应该很容易。

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()

enter image description here