Python_画boxplot 盒图/箱线图

Boxplot图的介绍

箱形图(Box-plot)又称为盒须图/盒式图/箱线图,是一种用作显示一组数据分散情况的统计图。这自然让人想到分位数的概念, 不错, boxplot就是通过分位数来直观展示数据的分散程度。
在这里插入图片描述
如上图,几个重要的参数:
下边缘(Q1),表示最小值;
下四分位数(Q2),又称“第一四分位数”,等于该样本中所有数值由小到大排列后第25%的数字;
中位数(Q3),又称“第二四分位数”等于该样本中所有数值由小到大排列后第50%的数字;
上四分位数(Q4),又称“第三四分位数”等于该样本中所有数值由小到大排列后第75%的数字;
上边缘(Q5),表述最大值。
极端异常值,即超出四分位数差3倍距离的异常值,用实心点表示;较为温和的异常值,即处于1.5倍-3倍四分位数差之间的异常值,用空心点表示

API介绍

在这里插入图片描述
参数:
x: Array 或者向量序列, Array的话每一行对应一个box, 序列list的话每个子list对应一个box;
labels: 每个box的label, 与x对应
patch_artist: 是否填充box
vert: 控制图的呈现方向 (水平或者垂直)
widths: 指定每个box的宽度

示例Demo

Demo 1: 绘制简单的Boxplot

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Polygon


# Fixing random state for reproducibility
np.random.seed(19680801)

# fake up some data
spread = np.random.rand(50) * 100
center = np.ones(25) * 50
flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100
data = np.concatenate((spread, center, flier_high, flier_low))

fig, axs = plt.subplots(2, 3)

# basic plot
axs[0, 0].boxplot(data)
axs[0, 0].set_title('basic plot')

# notched plot
axs[0, 1].boxplot(data, 1)
axs[0, 1].set_title('notched plot')

# change outlier point symbols
axs[0, 2].boxplot(data, 0, 'gD')
axs[0, 2].set_title('change outlier\npoint symbols')

# don't show outlier points
axs[1, 0].boxplot(data, 0, '')
axs[1, 0].set_title("don't show\noutlier points")

# horizontal boxes
axs[1, 1].boxplot(data, 0, 'rs', 0)
axs[1, 1].set_title('horizontal boxes')

# change whisker length
axs[1, 2].boxplot(data, 0, 'rs', 0, 0.75)
axs[1, 2].set_title('change whisker length')

fig.subplots_adjust(left=0.08, right=0.98, bottom=0.05, top=0.9,
                    hspace=0.4, wspace=0.3)

# fake up some more data
spread = np.random.rand(50) * 100
center = np.ones(25) * 40
flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100
d2 = np.concatenate((spread, center, flier_high, flier_low))
# Making a 2-D array only works if all the columns are the
# same length.  If they are not, then use a list instead.
# This is actually more efficient because boxplot converts
# a 2-D array into a list of vectors internally anyway.
data = [data, d2, d2[::2]]

# Multiple box plots on one Axes
fig, ax = plt.subplots()
ax.boxplot(data)

plt.show()

效果:
在这里插入图片描述

Demo 2:复杂的Boxplot, 为每个boxplot指定不同的颜色

一些小技巧
(1)x_tick的斜体显示
主要是通过ax.text方法的transform参数来指定的:
ax.text(pos[tick], .95, upper_labels[tick],transform=ax.get_xaxis_transform(),
其中ax:
ax.set_xticklabels(np.repeat(random_dists, 2),
rotation=45, fontsize=8)
可以看到旋转角度为45度。
(2)不同的boxplot显示不同的颜色

random_dists = ['Normal(1, 1)', 'Lognormal(1, 1)', 'Exp(1)', 'Gumbel(6, 4)',
                'Triangular(2, 9, 11)']
N = 500

norm = np.random.normal(1, 1, N)
logn = np.random.lognormal(1, 1, N)
expo = np.random.exponential(1, N)
gumb = np.random.gumbel(6, 4, N)
tria = np.random.triangular(2, 9, 11, N)

# Generate some random indices that we'll use to resample the original data
# arrays. For code brevity, just use the same random indices for each array
bootstrap_indices = np.random.randint(0, N, N)
data = [
    norm, norm[bootstrap_indices],
    logn, logn[bootstrap_indices],
    expo, expo[bootstrap_indices],
    gumb, gumb[bootstrap_indices],
    tria, tria[bootstrap_indices],
]

fig, ax1 = plt.subplots(figsize=(10, 6))
fig.canvas.manager.set_window_title('A Boxplot Example')
fig.subplots_adjust(left=0.075, right=0.95, top=0.9, bottom=0.25)

bp = ax1.boxplot(data, notch=0, sym='+', vert=1, whis=1.5)
plt.setp(bp['boxes'], color='black')
plt.setp(bp['whiskers'], color='black')
plt.setp(bp['fliers'], color='red', marker='+')

# Add a horizontal grid to the plot, but make it very light in color
# so we can use it for reading data values but not be distracting
ax1.yaxis.grid(True, linestyle='-', which='major', color='lightgrey',
               alpha=0.5)

ax1.set(
    axisbelow=True,  # Hide the grid behind plot objects
    title='Comparison of IID Bootstrap Resampling Across Five Distributions',
    xlabel='Distribution',
    ylabel='Value',
)

# Now fill the boxes with desired colors
box_colors = ['darkkhaki', 'royalblue']
num_boxes = len(data)
medians = np.empty(num_boxes)
for i in range(num_boxes):
    box = bp['boxes'][i]
    box_x = []
    box_y = []
    for j in range(5):
        box_x.append(box.get_xdata()[j])
        box_y.append(box.get_ydata()[j])
    box_coords = np.column_stack([box_x, box_y])
    # Alternate between Dark Khaki and Royal Blue
    ax1.add_patch(Polygon(box_coords, facecolor=box_colors[i % 2]))
    # Now draw the median lines back over what we just filled in
    med = bp['medians'][i]
    median_x = []
    median_y = []
    for j in range(2):
        median_x.append(med.get_xdata()[j])
        median_y.append(med.get_ydata()[j])
        ax1.plot(median_x, median_y, 'k')
    medians[i] = median_y[0]
    # Finally, overplot the sample averages, with horizontal alignment
    # in the center of each box
    ax1.plot(np.average(med.get_xdata()), np.average(data[i]),
             color='w', marker='*', markeredgecolor='k')

# Set the axes ranges and axes labels
ax1.set_xlim(0.5, num_boxes + 0.5)
top = 40
bottom = -5
ax1.set_ylim(bottom, top)
ax1.set_xticklabels(np.repeat(random_dists, 2),
                    rotation=45, fontsize=8)

# Due to the Y-axis scale being different across samples, it can be
# hard to compare differences in medians across the samples. Add upper
# X-axis tick labels with the sample medians to aid in comparison
# (just use two decimal places of precision)
pos = np.arange(num_boxes) + 1
upper_labels = [str(round(s, 2)) for s in medians]
weights = ['bold', 'semibold']
for tick, label in zip(range(num_boxes), ax1.get_xticklabels()):
    k = tick % 2
    ax1.text(pos[tick], .95, upper_labels[tick],
             transform=ax1.get_xaxis_transform(),
             horizontalalignment='center', size='x-small',
             weight=weights[k], color=box_colors[k])

# Finally, add a basic legend
fig.text(0.80, 0.08, f'{N} Random Numbers',
         backgroundcolor=box_colors[0], color='black', weight='roman',
         size='x-small')
fig.text(0.80, 0.045, 'IID Bootstrap Resample',
         backgroundcolor=box_colors[1],
         color='white', weight='roman', size='x-small')
fig.text(0.80, 0.015, '*', color='white', backgroundcolor='silver',
         weight='roman', size='medium')
fig.text(0.815, 0.013, ' Average Value', color='black', weight='roman',
         size='x-small')

plt.show()

效果:
在这里插入图片描述

References

1.https://matplotlib.org/stable/gallery/statistics/boxplot_demo.html#sphx-glr-gallery-statistics-boxplot-demo-py

  • 5
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: Python中可以使用matplotlib库中的boxplot函数来绘制多个箱线。 首先,需要准备好数据,将需要绘制的数据按照不同的组别分开,存储在一个字典中。然后,使用boxplot函数,将字典中的数据传入,设置参数来调整形的样式和布局,最后显示形即可。 例如,下面的代码演示了如何绘制三个组别的箱线: ```python import matplotlib.pyplot as plt # 准备数据 data = { 'Group A': [1, 2, 3, 4, 5], 'Group B': [2, 3, 4, 5, 6], 'Group C': [3, 4, 5, 6, 7] } # 绘制箱线 fig, ax = plt.subplots() ax.boxplot(data.values()) ax.set_xticklabels(data.keys()) ax.set_title('Boxplot of Three Groups') ax.set_xlabel('Group') ax.set_ylabel('Value') # 显示形 plt.show() ``` 运行上述代码,即可得到如下的箱线: ![boxplot.png](https://cdn.jsdelivr.net/gh/feiyuu/img/2022/20220113110239.png) ### 回答2: 箱线是一种用于展示数据分布特征的可视化工具。它通过展示数据的五数概括,包括最小值、第一四分位数、中位数、第三四分位数和最大值,来帮助我们了解数据的中心趋势、离散程度和异常值。 在Python中,我们可以使用matplotlib库的boxplot函数来绘制箱线。如果我们要展示多个数据集的箱线,我们可以把它们放在同一张上,并用不同的颜色或样式来区分。 下面是一个绘制多个箱线的例子: ```python import matplotlib.pyplot as plt import numpy as np # 生成三个数据集 data1 = np.random.normal(0, 1, 100) data2 = np.random.normal(1, 1, 100) data3 = np.random.normal(2, 1, 100) # 绘制箱线 plt.boxplot([data1, data2, data3], labels=['data1', 'data2', 'data3']) # 设置x轴标签和标题 plt.xlabel('Dataset') plt.ylabel('Value') plt.title('Boxplot of Multiple Datasets') # 显示形 plt.show() ``` 在这个例子中,我们使用numpy库生成了三个数据集,并把它们放在同一张上绘制了箱线。我们使用boxplot函数的第一个参数传入一个包含多个数据集的列表,用labels参数指定了每个数据集的名称。最后,我们设置了x轴标签、y轴标签和形标题,并使用show函数显示了形。 通过多个箱线的比较,我们可以更容易地发现不同数据集之间的差异和相似之处,进而对数据进行分析和处理。 ### 回答3: Python的Matplotlib库提供了一个很好的函数来创建多个箱线。箱线Boxplot)是一种常用的表,常用于展示数据的中位数、第一四分位数、第三四分位数和异常值。它非常适合用于比较多个数据集之间的分布和差异。 要创建多个箱线,可以使用Matplotlib的subplot函数,该函数可以在一个Figure对象上创建多个绘区域,每个区域包含一个单独的子。为创建多个箱线,首先要创建一个新的Figure对象,设置Figure的大小和标题。然后调用subplot函数来设置绘区域的行和列数,并选择要在每个区域中绘制的箱线的位置。 在每个子中绘制箱线,可以使用Matplotlib的boxplot函数。boxplot函数接收一个数据列表,每个列表中包含了一个数据集中的所有数值。在箱线的每个箱子内应包含的数据集可以通过指定labels参数来指定,该参数是一个列表,其中包含每个数据集的名称。 在创建完所有的箱线之后,可以使用Matplotlib的suptitle函数来添加Figure的总体标题。最后,调用show函数来显示所有的箱线。 以下是一个简单的Python代码示例来展示如何创建多个箱线: ``` import matplotlib.pyplot as plt # 数据 data1 = [1, 2, 3, 4, 5] data2 = [2, 3, 4, 5, 6] data3 = [3, 4, 5, 6, 7] # 创建Figure对象 fig = plt.figure(figsize =(10, 7)) # 设置Figure对象的标题 fig.suptitle('Multiple Boxplots') # 添加子,并在每个子中绘制箱线 ax1 = fig.add_subplot(131) ax1.boxplot(data1, labels =['Data 1']) ax2 = fig.add_subplot(132) ax2.boxplot(data2, labels =['Data 2']) ax3 = fig.add_subplot(133) ax3.boxplot(data3, labels =['Data 3']) # 显示形 plt.show() ``` 在以上示例中,我们首先导入了Matplotlib库。然后定义了三个数据集,分别为data1、data2和data3。接下来,我们创建了一个新的Figure对象,并设置了Figure的大小和标题。然后使用add_subplot函数创建了三个子,分别存储在变量ax1、ax2和ax3中。 在每个子中,我们使用boxplot函数绘制了一个箱线,并指定了每个数据集的名称。最后,使用suptitle函数添加Figure的总体标题,然后使用show函数显示所有绘区域的内容。 以上就是如何在Python中使用Matplotlib创建多个箱线的简单示例。通过使用subplot函数创建多个绘区域,并在每个区域中使用boxplot函数绘制数据集的箱线,我们可以方便地比较不同数据集之间的分布和差异。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MasterQKK 被注册

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值