对齐y标签

这里显示了两种方法,一种是使用对 Figure.align_ylabels 的简短调用,另一种是使用手动方式来对齐标签。

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. def make_plot(axs):
  4. box = dict(facecolor='yellow', pad=5, alpha=0.2)
  5. # Fixing random state for reproducibility
  6. np.random.seed(19680801)
  7. ax1 = axs[0, 0]
  8. ax1.plot(2000*np.random.rand(10))
  9. ax1.set_title('ylabels not aligned')
  10. ax1.set_ylabel('misaligned 1', bbox=box)
  11. ax1.set_ylim(0, 2000)
  12. ax3 = axs[1, 0]
  13. ax3.set_ylabel('misaligned 2', bbox=box)
  14. ax3.plot(np.random.rand(10))
  15. ax2 = axs[0, 1]
  16. ax2.set_title('ylabels aligned')
  17. ax2.plot(2000*np.random.rand(10))
  18. ax2.set_ylabel('aligned 1', bbox=box)
  19. ax2.set_ylim(0, 2000)
  20. ax4 = axs[1, 1]
  21. ax4.plot(np.random.rand(10))
  22. ax4.set_ylabel('aligned 2', bbox=box)
  23. # Plot 1:
  24. fig, axs = plt.subplots(2, 2)
  25. fig.subplots_adjust(left=0.2, wspace=0.6)
  26. make_plot(axs)
  27. # just align the last column of axes:
  28. fig.align_ylabels(axs[:, 1])
  29. plt.show()

对齐y标签示例

另见 Figure.align_ylabels and Figure.align_labels for a direct method of doing the same thing. Also Aligning Labels

或者,我们可以使用y轴对象的set_label_coords方法手动在子图之间手动对齐轴标签。请注意,这需要我们知道硬编码的良好偏移值。

  1. fig, axs = plt.subplots(2, 2)
  2. fig.subplots_adjust(left=0.2, wspace=0.6)
  3. make_plot(axs)
  4. labelx = -0.3 # axes coords
  5. for j in range(2):
  6. axs[j, 1].yaxis.set_label_coords(labelx, 0.5)
  7. plt.show()

对齐y标签示例2

参考

此示例中显示了以下函数,方法,类和模块的使用:

  1. import matplotlib
  2. matplotlib.figure.Figure.align_ylabels
  3. matplotlib.axis.Axis.set_label_coords
  4. matplotlib.axes.Axes.plot
  5. matplotlib.pyplot.plot
  6. matplotlib.axes.Axes.set_title
  7. matplotlib.axes.Axes.set_ylabel
  8. matplotlib.axes.Axes.set_ylim

下载这个示例