如何在 Matplotlib 中為 3D 柱狀圖建立圖例?


要在 matplotlib 中為 3D 柱狀圖建立圖例,我們可以繪製 3D 柱狀圖並使用 legend() 方法放置一個圖例。

步驟

  • 設定圖形大小並調整子圖之間和子圖周圍的間距。
  • 使用 figure() 方法建立一個新圖形或啟用一個現有圖形。
  • 作為子圖排列的一部分,將一個座標軸新增到圖形中。
  • 使用 numpy 建立資料 x3、y3、z3、dx、dy 和 dz 的列表。
  • 使用 bar3d() 方法繪製一個 3D 柱狀圖。
  • 為圖例放置建立一個矩形座標軸。
  • 使用 legend() 方法放置柱狀圖的圖例。
  • 要顯示圖形,請使用 show() 方法。

示例

import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')
x3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y3 = [5, 6, 7, 8, 2, 5, 6, 3, 7, 2]
z3 = np.zeros(10)
dx = np.ones(10)
dy = np.ones(10)
dz = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ax1.bar3d(x3, y3, z3, dx, dy, dz, color="green")
b1 = plt.Rectangle((0, 0), 1, 1, fc="green")
ax1.bar3d(y3, x3, z3, dx, dy, dz, color="red")
b2 = plt.Rectangle((0, 0), 1, 1, fc="red")
ax1.legend([b1, b2], ['type1', 'type2'])
plt.show()

輸出

更新於: 2021-06-01

1 千次 + 瀏覽

開始你的 職業生涯

完成課程認證

開始
廣告
© . All rights reserved.