在同一轴线上添加包含多个图表的 Matplotlib 箱线图


为在同一轴线上包含多个图表的 matplotlib 箱线图添加图例,我们可以采取以下步骤 -

  • 设置图形大小并调整子图之间的和围绕子图的空白。

  • 使用 numpy 创建随机数据 ab

  • 使用 figure() 方法创建一个新图形或激活一个现有的图形。

  • 将轴作为子图布局添加到当前图形。

  • 使用 boxplot() 方法以不同的面填充颜色绘制矩形和条形图。

  • 为图例放置位置,使用 legend() 方法使用两个箱线图(bp1bp2)和图例元素的有序标签。

  • 使用 show() 方法显示图形。

示例

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

a = np.random.rand(100, 2)
b = np.random.rand(100, 2)

fig = plt.figure()
ax = fig.add_subplot(111)

bp1 = ax.boxplot(a, positions=[1, 3], notch=True, widths=0.35, patch_artist=True, boxprops=dict(facecolor="C0"))
bp2 = ax.boxplot(a, positions=[0, 2], notch=True, widths=0.35, patch_artist=True, boxprops=dict(facecolor="C2"))
ax.legend([bp1["boxes"][0], bp2["boxes"][0]], ["Box Plot 1", "Box Plot 2"], loc='upper right')

plt.show()

输出

更新于: 2021-06-03

3 千次浏览

开启你的职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.