如何强制 Matplotlib 将 X 轴上的值显示为整数?

pythonserver side programmingprogramming更新于 2025/8/8 19:24:17

要强制 matplotlib 将 X 轴上的值显示为整数,我们可以采取以下步骤 −

  • 设置图形大小并调整子图之间和周围的填充。
  • 创建两个数据点列表 x 和 y。
  • 使用 plot() 方法绘制 x 和 y。
  • 为 X 轴上的整数勾选创建一个新列表。使用 ma​​th.floor() 和 ma​​th.ceil() 删除小数,并在列表中仅包含整数。
  • 设置 x 和 y 标签。
  • 设置图形的标题。
  • 要显示图形,请使用 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()

输出


相关文章


有用资源