如何在 Python/Matplotlib 中將文字放置在等比例圖形的角上?


如要在 matplotlib 中將文字放置在等比例圖形的角上,我們可以執行以下步驟 −

  • 設定圖形大小並調整子圖之間和周圍的間距。

  • 使用 subplots() 方法建立圖形和一組子圖。

  • 使用 numpy 建立 x 資料點。

  • 使用 plot() 方法在 axis ax1 上繪製 x。

  • 使用 plot() 方法在 ax2 上繪製 x 和 2*x。

  • 如要將文字放在圖形的角上,針對不同的軸使用 annotate() 方法。

  • 如要顯示圖表,使用 show() 方法。

示例

from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, axes = plt.subplots(2)
x = np.linspace(-2, 2, 10)
axes[0].plot(x)
axes[1].plot(x, 2*x)
for ax in axes:
   ax.annotate('Straight Line', xy=(1, 0),xycoords='axes fraction', fontsize=10, horizontalalignment='right', verticalalignment='bottom')
plt.show()

輸出

更新時間: 2021-06-03

2K+ 次瀏覽

開啟您的職業生涯

完成課程,獲得認證

開始吧
廣告