在 matplotlib 中建立帶有缺口的水平條形圖的方法


要在 matplotlib 中建立帶有缺口的水平條形圖,我們可以採取以下步驟 −

  • 設定圖形大小,並調整子圖之間和周圍的填充。
  • 建立一個圖形和一組子圖。
  • 繪製水平矩形序列。
  • 縮放 X 和 Y 軸限制。
  • 配置網格線。
  • 註釋帶有缺口的條形圖。
  • 若要顯示圖形,請使用 show() 方法。

範例

import matplotlib.pyplot as plt

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

fig, ax = plt.subplots()

# Horizontal sequence of rectangles
ax.broken_barh([(110, 30), (150, 10)], (10, 9), facecolors='tab:blue')
ax.broken_barh([(10, 50), (100, 20), (130, 10)], (20, 9),
   facecolors=('tab:orange', 'tab:green', 'tab:red'))

# Scale X and Y axes limits
ax.set_ylim(5, 35)
ax.set_xlim(0, 200)

# Configure the grid lines
ax.grid(True)

# Annotate the broken bars
ax.annotate('race interrupted', (61, 25),
   xytext=(0.8, 0.9), textcoords='axes fraction',
   arrowprops=dict(facecolor='black', shrink=0.05),
   fontsize=16,
   horizontalalignment='right', verticalalignment='top')

plt.show()

輸出

將生成以下輸出

更新於:22-Sep-2021

224 次瀏覽

啟動你的 事業

完成該課程獲得認證

開始
廣告