【问题标题】:Matplotlib subplots: legend and axis-scaleMatplotlib 子图:图例和轴比例
【发布时间】:2014-10-30 13:52:17
【问题描述】:

我正在以这种方式绘制 4 个子图(即 2 行 2 列):

fig1= plt.figure(figsize=(8,6))
ax1 = fig1.add_subplot(221)
ax1.errorbar((r1),(xi1),fmt='',yerr=(low_err_1,upp_err_1),ls='none',color='black')
ax1.scatter((r1),(xi1),c='red',marker="o",s=30,label= r'$\xi(r)$ $0.0<z<0.5$')
ax1.plot((r1),(curve_y_1),'--',label='fit $0.0<z<0.5$')
ax1.set_xscale('log')
ax1.set_yscale('log')

ax2 = fig1.add_subplot(222)
ax2.errorbar((r2),(xi2),fmt='',yerr=(low_err_2,upp_err_2),ls='none',color='black')
ax2.scatter((r2),(xi2),c='blue',marker="o",s=30,label=r'$\xi(r)$ $0.5<z<1.0$')
ax2.plot((r2),(curve_y_2),'--',label='fit $0.5<z<1.0$')
ax2.set_xscale('log')
ax2.set_yscale('log')

ax3 = fig1.add_subplot(223)
ax3.errorbar((r3),(xi3),fmt='',yerr=(low_err_3,upp_err_3),ls='none',color='black')
ax3.scatter((r3),(xi3),c='yellow',marker="o",s=30,label=r'$\xi(r)$ $1.0<z<1.5$')
ax3.plot((r3),(curve_y_3),'--',label='fit $1.0<z<1.5$')
ax3.set_xscale('log')
ax3.set_yscale('log')

ax4 = fig1.add_subplot(224)
ax4.errorbar((r4),(xi4),fmt='',yerr=(low_err_4,upp_err_4),ls='none',color='black')
ax4.scatter((r4),(xi4),c='black',marker="o",s=30,label=r'$\xi(r)$ $1.5<z<2.0$')
ax4.plot((r4),(curve_y_4),'--',label='fit $1.5<z<2.0$')
ax4.set_xscale('log')
ax4.set_yscale('log')

我的问题是:

  1. 有没有办法使用单个(通用)命令为所有这些子图添加图例,而不是为每个子图分别输入 ax1.legend(loc = 'best')ax2.legend(loc = 'best') 等?
  2. 我想使用单个(通用)命令为每个子图设置对数缩放。如您所见,现在我正在分别设置轴刻度以记录每个子图。

【问题讨论】:

    标签: python matplotlib subplot


    【解决方案1】:

    只需定义一个坐标轴格式化函数:

    def style_ax(ax):
       ax.legend(loc='best')
       ax.set_yscale('log')
       ax.set_xscale('log')
    

    完成后调用它:

    for ax in [ax1, ax2, ax3, ax4]:
       style_ax(ax)
    

    【讨论】: