设置matplotlib x限制的格式

2024-04-27 04:28:44 发布

您现在位置:Python中文网/ 问答频道 /正文

x = np.linspace(2000.0, 2018.0, num = 18)

for i in range(len(x)):
    x[i]=int(x[i])


for i in range(2000, 2018):
    y.append(dic[str(i)])


fig, ax = plt.subplots()

ax.plot(x, y, marker='o', color='r')

# set title

# set label for x

# set label for y

print(ax.get_xlim())

return ax

我试着画一个18点,其中x极限应该在(2000.0)到(2018.0)之间。有些代码是隐藏的,但我只是张贴的关键部分。当我打印出结果时,xlimit是

(1999.0999999999999, 2018.9000000000001)

不是

(2000.0, 2018.0)

请告诉我我做错了什么。你知道吗


Tags: inforlennpfigrangeaxnum
2条回答

你需要自己设置xlim。matplotlib自动选择限制和记号。你知道吗

所以你需要使用

ax.set_xlim([x[0],x[-1]])

xlim就是你想要的。你知道吗

见下图enter image description here

你没有做错什么,但是你可能对情节的界限有错误的期望。你知道吗

默认情况下,matplotlib在绘图的每一侧保留5%的边距。因此,如果您的数据在[x.min(), x.max()] == [2000.0, 2018.0]范围内,您的限制将是

[x.min()-0.05*(x.max()-x.min()), x.max()+0.05*(x.max()-x.min())] == [1999.1, 2018.9]

如果您不想在数据周围有任何填充,请使用ax.margins(x=0)。在这种情况下print(ax.get_xlim())将打印(2000.0, 2018.0)

完整示例:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(2000.0, 2018.0, num = 19)
y = np.cumsum(np.random.rand(len(x)))

x = x.astype(int)

fig, ax = plt.subplots()

ax.plot(x, y, marker='o', color='r')
ax.margins(x=0)

print(ax.get_xlim())

相关问题 更多 >