Matplotlib绘图与坐标轴之间的间距问题

6

我正在尝试使用matplolib创建一个图形,其中坐标轴和实际绘图之间有一些填充。

以下是我的示例代码:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(1)

x = np.linspace(0, 1)
y = np.sin(4 * np.pi * x) * np.exp(-5 * x)

plt.plot(x, y, 'r')
plt.grid(True)


plt.show()

以下是我想要得到的内容:

带有x和y偏移的绘图

2个回答

17
在您的情况下,最简单的方法是使用ax.margins(some_percentage)或等效的plt.margins(some_percentage)
例如:
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x = np.linspace(0, 1)
y = np.sin(4 * np.pi * x) * np.exp(-5 * x)

ax.plot(x, y, 'r')
ax.grid(True)
ax.margins(0.05) # 5% padding in all directions

plt.show()

输入图像描述


1
请注意,边距设置适用于自动缩放;如果已关闭此功能,则需要重新启用以使边距生效:ax.autoscale(True) - SpinUp __ A Davis

0
你可以使用xlim和ylim来设置图形的限制范围。 在这里查看。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接