matplotlib 具有共同x和y标签以及x轴下的共同图例的子图

6fe3ivhb  于 2023-03-09  发布在  其他
关注(0)|答案(1)|浏览(198)

我试图绘制一个子图,在图的底部显示一个通用图例,在一个通用x轴标签的下面,还有一个通用y轴标签。我有两种方法几乎可以让它工作,除了第一种方法是通用y轴标签与轴刻度标签重叠,而第二种方法我不知道如何让图例显示在图上(它挂在页面上)。
选项2,使用较新的supx/ylabel,在子情节和标签之间也放置了太多的空间-但我认为这是可以修复的(关于这一点有很多问题)。
这些只是示例图,实际的图在标签中使用更多的小数位,所以重叠是相当大的。我也可能设置图形大小来打印(和保存)图很好。

微波辐射计

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # Some points to plot
  4. x = np.linspace(0, 2 * np.pi, 400)
  5. y = np.sin(x ** 2)
  6. z = np.sin((1.03* x) ** 2)
  7. #option 1 - problem is with my real data the common y label is over the labels of the left hand plot
  8. fig, axs = plt.subplots(2, 2)
  9. axs[0, 0].plot(x, y)
  10. axs[0, 0].plot(x, z, '--')
  11. axs[0, 1].plot(x, y)
  12. axs[0, 1].plot(x, z, '--')
  13. axs[1, 0].plot(x, -y)
  14. axs[1, 0].plot(x, -z, '--')
  15. axs[1, 1].plot(x, -y)
  16. axs[1, 1].plot(x, -z, '--')
  17. fig.add_subplot(111, frameon=False)
  18. plt.tick_params(labelcolor='none', which='both', top=False, bottom=False, left=False, right=False)
  19. plt.xlabel("The X label")
  20. plt.ylabel("The Y label")
  21. fig.subplots_adjust(bottom=0.2)
  22. labels = ["A","B"]
  23. fig.legend(labels,loc='lower center', ncol=len(labels), bbox_to_anchor=(0.55, 0))
  24. fig.tight_layout()
  25. # Option 2 - problem is I can't get the legend to show (it is off the page)
  26. fig, axs = plt.subplots(2, 2)
  27. axs[0, 0].plot(x, y)
  28. axs[0, 0].plot(x, z, '--')
  29. axs[0, 1].plot(x, y)
  30. axs[0, 1].plot(x, z, '--')
  31. axs[1, 0].plot(x, -y)
  32. axs[1, 0].plot(x, -z, '--')
  33. axs[1, 1].plot(x, -y)
  34. axs[1, 1].plot(x, -z, '--')
  35. fig.supxlabel("The X label")
  36. fig.supylabel("The Y label")
  37. fig.subplots_adjust(bottom=0.2)
  38. labels = ["A","B"]
  39. fig.legend(labels,loc='lower center', ncol=len(labels), bbox_to_anchor=(0.55, 0))
  40. fig.tight_layout()
utugiqy6

utugiqy61#

第一个选项几乎已经完成,将labelpad添加到ax.set_xlabel()ax.set_ylabel()调用应该可以解决您的问题。
这是最新版本。

  1. # [...]
  2. fig, axs = plt.subplots(2, 2, figsize=(16, 8), tight_layout=True)
  3. # [...]
  4. # Create the new axis for marginal X and Y labels
  5. ax = fig.add_subplot(111, frameon=False)
  6. # Disable ticks. using ax.tick_params() works as well
  7. ax.set_xticks([])
  8. ax.set_yticks([])
  9. # Set X and Y label. Add labelpad so that the text does not overlap the ticks
  10. ax.set_xlabel("The X label", labelpad=20, fontsize=12)
  11. ax.set_ylabel("The Y label", labelpad=40, fontsize=12)
  12. # Set fig legend as you did
  13. labels = ["A","B"]
  14. fig.legend(labels, loc='lower center', ncol=len(labels), bbox_to_anchor=(0.55, 0))

展开查看全部

相关问题