【问题标题】:imshow() subplots generate unwanted white spacesimshow() 子图生成不需要的空白
【发布时间】:2016-01-27 13:06:51
【问题描述】:

当绘制两个(或更多)子图时,图中(所有四个边上)有大面积的空白区域,如下所示:

以下是我用来绘制它的代码。

from pylab import *
from matplotlib import rc, rcParams
import matplotlib.pyplot as plt

for kk in range(57,58):
    fn_i=str(kk)
    image_file_1='RedshiftOutput00'+fn_i+'_Slice_z_RadioPowerDSA.png'
    image_file_2='RedshiftOutput00'+fn_i+'_Slice_z_RadioPowerTRA.png'
    image_file_3='RedshiftOutput00'+fn_i+'_Slice_z_RadioPowerDSA+TRA.png'

    image_1 = plt.imread(image_file_1)
    image_2 = plt.imread(image_file_2)
    image_3 = plt.imread(image_file_3)      

    ax1 = subplot(131)
    plt.imshow(image_1)
    plt.axis('off')  # clear x- and y-axes

    ax2 = subplot(132)
    plt.imshow(image_2)
    plt.axis('off')  # clear x- and y-axes

    ax3 = subplot(133)
    plt.imshow(image_3)
    plt.axis('off')  # clear x- and y-axes

    plt.savefig('RedshiftOutput00'+fn_i+'_all.png')

我还上传了此代码中使用的 3 张图片,以使代码成为最小的工作示例

1)https://drive.google.com/file/d/0B6l5iRWTUbHWSTF2R3E1THBGeVk/view?usp=sharing

2)https://drive.google.com/file/d/0B6l5iRWTUbHWaFI4dHAzcWpiOEU/view?usp=sharing

3)https://drive.google.com/file/d/0B6l5iRWTUbHWaG8xclFlcGJNaUk/view?usp=sharing

我们怎样才能去掉这个空白?我尝试通过修复整个地块大小,仍然出现空白。

【问题讨论】:

  • 试试plt.tight_layout()

标签: python python-2.7 matplotlib whitespace imshow


【解决方案1】:

上面梅尔的评论(使用plt.tight_layout())适用于许多情况,但有时您需要更多控制。要更精细地操作轴(有用,例如,当您有很多颜色条或 twin-ned 轴时),您可以使用 plt.subplots_adjust()GridSpec 对象。

GridSpec 对象允许您指定各个轴的水平和垂直范围,以及它们的比例宽度和高度和间距。 subplots_adjust() 在你已经在它们上绘制了东西之后移动你的轴。我更喜欢使用第一个选项,但两者都是documentedwell

它也可能有助于愚弄你的身材。如果宽度方向有很多空白,请缩小图形的宽度。

这是我用来设置最近的情节的一些示例代码:

gs = gridspec.GridSpec(
        nrows=1, ncols=3, left=0.1, bottom=0.25, right=0.95, top=0.95,
        wspace=0.05, hspace=0., width_ratios=[1, 1, 1])
NII_ax = plt.subplot(gs[0])
SII_ax = plt.subplot(gs[1])
OI_ax = plt.subplot(gs[2])

结果:

然后,如果您需要颜色条,请将 GridSpec 中的 right 参数调整为 0.85,并将 fig.add_axes() 与列表 [left_lim, bottom, width, height] 一起使用,并将其用作 fig.colorbar() 的轴参数

【讨论】:

  • 使用 gridspec.GridSpec 问题已经解决了... :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-28
  • 1970-01-01
相关资源
最近更新 更多