matplotlib 如何在箱线图和须线图中打印箱线图、须线图和离群值

mtb9vblg  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(159)

我已经为我的数据绘制了一个盒须图

我的验证码:

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)

我得到了一个如下的图:

**我想做的是:**在图上打印须线、离群值(红色菱形)、四分位数和中位数的值。

cgfeq70w

cgfeq70w1#

ax.boxplot返回一个字典,其中包含在制作盒须图时绘制的所有线条。一个选项是询问此字典,并根据其包含的信息创建标签。相关键是:

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

请注意,下面的函数只适用于单个箱线图(如果您一次性创建多个箱线图,则需要更加小心如何从字典中获取信息)。
另一种方法是从数据数组本身查找信息(查找中位数和IQR很容易)。我不确定matplotlib如何确定什么是传单以及caps应该放在哪里。如果你想这样做,修改下面的函数应该很容易。

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

相关问题