Axes.margins缩放粘性

此示例中的第一个图显示了如何使用边距)而不是set_xlimset_ylim放大和缩小绘图。第二个图展示了某些方法和艺术家引入的边缘“粘性”的概念,以及如何有效地解决这个问题。

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. def f(t):
  4. return np.exp(-t) * np.cos(2*np.pi*t)
  5. t1 = np.arange(0.0, 3.0, 0.01)
  6. ax1 = plt.subplot(212)
  7. ax1.margins(0.05) # Default margin is 0.05, value 0 means fit
  8. ax1.plot(t1, f(t1), 'k')
  9. ax2 = plt.subplot(221)
  10. ax2.margins(2, 2) # Values >0.0 zoom out
  11. ax2.plot(t1, f(t1), 'r')
  12. ax2.set_title('Zoomed out')
  13. ax3 = plt.subplot(222)
  14. ax3.margins(x=0, y=-0.25) # Values in (-0.5, 0.0) zooms in to center
  15. ax3.plot(t1, f(t1), 'g')
  16. ax3.set_title('Zoomed in')
  17. plt.show()

Axes.margins示例

论某些绘图方法的“粘性”

一些绘图功能使轴限制为 “粘性(stickiness)” 或不受边距方法的影响。 例如,imshow 和pcolor期望用户希望限制在图中所示的像素周围紧密。 如果不需要此行为,则需要将 use_sticky_edges 设置为 False。请考虑以下示例:

一些绘图功能使轴限制“粘性(stickiness)”或免疫的边缘方法。例如,imShow和pcold期望用户希望限制紧在绘图中所示的像素周围。如果不需要此行为,则需要将use_clatice_edage设置为false。考虑以下示例:

  1. y, x = np.mgrid[:5, 1:6]
  2. poly_coords = [
  3. (0.25, 2.75), (3.25, 2.75),
  4. (2.25, 0.75), (0.25, 0.75)
  5. ]
  6. fig, (ax1, ax2) = plt.subplots(ncols=2)
  7. # Here we set the stickiness of the axes object...
  8. # ax1 we'll leave as the default, which uses sticky edges
  9. # and we'll turn off stickiness for ax2
  10. ax2.use_sticky_edges = False
  11. for ax, status in zip((ax1, ax2), ('Is', 'Is Not')):
  12. cells = ax.pcolor(x, y, x+y, cmap='inferno') # sticky
  13. ax.add_patch(
  14. plt.Polygon(poly_coords, color='forestgreen', alpha=0.5)
  15. ) # not sticky
  16. ax.margins(x=0.1, y=0.05)
  17. ax.set_aspect('equal')
  18. ax.set_title('{} Sticky'.format(status))
  19. plt.show()

Axes.margins示例2

参考

本例中显示了以下函数、方法的使用:

  1. import matplotlib
  2. matplotlib.axes.Axes.margins
  3. matplotlib.pyplot.margins
  4. matplotlib.axes.Axes.use_sticky_edges
  5. matplotlib.axes.Axes.pcolor
  6. matplotlib.pyplot.pcolor
  7. matplotlib.pyplot.Polygon

下载这个示例