如何強制 Matplotlib 以整數形式顯示 X 軸上的值?


要強制 Matplotlib 以整數形式顯示 X 軸上的值,我們可以採取以下步驟 −

  • 設定圖形大小並調整子圖之間和周圍的填充。
  • 建立兩個資料點列表,分別是 xy
  • 使用 plot() 方法繪製 xy
  • 建立一個新列表,只在 X 軸上顯示整數刻度。使用 math.floor()math.ceil() 刪除小數,並僅在列表中包含整數。
  • 設定 xy 標籤。
  • 設定圖形的標題。
  • 要顯示圖形,請使用 show() 方法。

示例

import math
from matplotlib import pyplot as plt

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

y = [0.17, 1.17, 2.98, 3.15, 4.11, 5.151]
x = [1.0, 1.75, 2.90, 3.15, 4.50, 5.50]

plt.plot(x, y)

new_list = range(math.floor(min(x)), math.ceil(max(x))+1)
plt.xticks(new_list)

plt.xlabel("X-axis ")
plt.ylabel("Y-axis ")

plt.title("Only Integers on the X-axis")

plt.show()

輸出

更新於: 08-Jul-2021

16K+ 瀏覽次數

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.