【问题标题】:Matplotlib padding between plot and axis绘图和轴之间的 Matplotlib 填充
【发布时间】:2015-12-29 08:14:27
【问题描述】:

我正在尝试在轴和实际绘图之间添加一些填充来制作 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()

这就是我想要得到的:

【问题讨论】:

    标签: python matplotlib plot


    【解决方案1】:

    在您的情况下,使用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()
    

    【讨论】:

    • 注意边距设置适用于自动缩放;如果此功能已关闭,则需要重新启用它才能使边距生效:ax.autoscale(True)
    【解决方案2】:

    您可以使用 xlim 和 ylim 设置绘图的限制。 见here

    【讨论】:

      猜你喜欢
      • 2022-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      • 1970-01-01
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多