如何强制 Matplotlib 以整数形式显示 X 轴上的值?
要强制 Matplotlib 以整数形式显示 X 轴上的值,我们可以采取以下步骤 −
- 设置图形大小并调整子图之间和周围的填充。
- 创建两个数据点列表,分别是 x 和 y。
- 使用 plot() 方法绘制 x 和 y。
- 创建一个新列表,只在 X 轴上显示整数刻度。使用 math.floor() 和 math.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()输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP