在同一軸線上新增包含多個圖表的 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 千次瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始
廣告