如何强制 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.