Python 2.7 如何从子绘图中完全删除绘图并正确调整大小?

Python 2.7 如何从子绘图中完全删除绘图并正确调整大小?,python-2.7,matplotlib,jupyter-notebook,subplot,Python 2.7,Matplotlib,Jupyter Notebook,Subplot,我试图为即将发表的论文创建一个角点图,但我遇到了困难。我正在创建一个N x N的子地块数组(目前,N=6),然后删除其中的一半多一点。问题是,在我删除无关的子图后,图形似乎不会自行调整大小,因此,当我稍后使用虚拟子图添加图例时,它存在于删除的子图的完整行和列所在的区域中,从而放大了图形。我已对此进行了数小时的研究,但尚未找到解决方案。以下是MWE: import matplotlib.pyplot as plt %matplotlib notebook n_char = 8 # Set up

我试图为即将发表的论文创建一个角点图,但我遇到了困难。我正在创建一个N x N的子地块数组(目前,N=6),然后删除其中的一半多一点。问题是,在我删除无关的子图后,图形似乎不会自行调整大小,因此,当我稍后使用虚拟子图添加图例时,它存在于删除的子图的完整行和列所在的区域中,从而放大了图形。我已对此进行了数小时的研究,但尚未找到解决方案。以下是MWE:

import matplotlib.pyplot as plt
%matplotlib notebook

n_char = 8

# Set up the main figure.
fig, ax = plt.subplots(n_char, n_char, figsize=(n_char, n_char))

# Get rid of the axis labels unless it's on the left-most column or bottom-most row.
for i in range(0, n_char):

    # For each row, loop over each column.
    for j in range(0, n_char):

        # If the plot isn't in the bottom-most row, get rid of the x-axis tick labels.
        if i != n_char - 1:
            ax[i, j].set_xticklabels([])

        # If the plot isn't in the left-most column, get rid of the y-axis tick labels.
        if j != 0:
            ax[i, j].set_yticklabels([])

# Remove the plots that are repetitive or boring (plotting against the same characteristic).
for i in range(0, n_char):

    # For each row, loop over each column.
    for j in range(0, n_char):

        # Delete the offending axes.
        if j >= i:
            ax[i, j].remove()

# Set the spacing between the plots to a much smaller value.
fig.subplots_adjust(hspace=0.00, wspace=0.00)

# Create a big plot for the legend.  Have the frame hidden.
fig.add_subplot(111, frameon=False, xticks=[], yticks=[], xticklabels=[], yticklabels=[])

# Create some dummy data to serve as the source of the legend.
plt.scatter([10], [10], color="k", s=5, zorder=2, label="Targets")

# Set the x-axis limits such that the dummy data point is invisible.
fig.gca().set_xlim(-1, 1)

# Add the legend to the plot.  Have it located in the upper right.
plt.legend(scatterpoints=1, loc="upper right", fontsize=5)

# Save the final plot.
fig.savefig("./../Code Output/Other Plots/Corner_Plot_Test.png", bbox_inches="tight", dpi=500)
我在这里研究了许多关于堆栈溢出的不同问题。两个最有希望的候选人是,但我发现由于大量的情节,这个解决方案不太可行(坦率地说,我没有完全理解这个解决方案)。我认为中的第一个答案也可能有效,因为我认为这是一个大小问题(即,图形没有调整大小,因此创建一个新的子批次就是创建一个原始图形大小的子批次),但它所做的只是调整整个图形的大小,因此也不起作用

为了提供帮助,我还将包括一个图像。我获取了上面代码的输出并对其进行了编辑,以显示我想要的内容:


我应该补充一点,如果我不添加子批,输出是我预期的(即,它的大小合适),因此在添加子批时会出现问题,即线
fig.add_子批(111,frameon=False,xticks=[],yticks=[],xticklabels=[],yticklabels=[],yticklabels=[])
使用
GridSpec
可能会有所帮助。 GridSpec用于指定要打印的轴阵列。可以在选项中将列的宽度和行的高度设置为比率。不需要的行应该具有非常小的高度比,而不需要的列应该具有非常小的宽度比。 以下是可运行代码和输出图:-

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
#import numpy as np

fig = plt.figure(figsize=(8, 8))
nn = 6

# will create gridspec of 6 rows, 6 columns
# 1st row will occupy v small heights
# last column will occupy v small widths

sm = 0.01            # the v small width/height
wh = (1.-sm)/(nn-1.) # useful width/height

gs = gridspec.GridSpec(nn, nn, width_ratios=[*[wh]*(nn-1), sm], \
                      height_ratios= [sm, *[wh]*(nn-1)])

cols, rows = nn, nn
ax = [[0 for i in range(cols)] for j in range(rows)] 

for ea in range(nn):
    for eb in range(nn):
        ax[ea][eb] = fig.add_subplot(gs[ea, eb])
        ax[ea][eb].set_xticklabels([])
        ax[ea][eb].set_yticklabels([])
        if eb>=ea:
            ax[ea][eb].remove()

# plot data on some axes
# note that axes on the first row (index=0) are gone
ax[2][0].plot([2,5,3,7])
ax[4][2].plot([2,3,7])

# make legend in upper-right axes (GridSpec's first row, last column)
# first index: 0
# second index: nn-1
rx, cx = 0, nn-1
ax[rx][cx] = fig.add_subplot(gs[rx,cx])
hdl = ax[rx][cx].scatter([10], [10], color="k", s=5, zorder=2, label="Targets")
ax[rx][cx].set_axis_off()
#ax[rx][cx].set_visible(True)  # already True
ax[rx][cx].set_xticklabels([])
ax[rx][cx].set_yticklabels([])

# plot legend
plt.legend(bbox_to_anchor=(1.0, 1.0), loc='upper right', borderaxespad=0.)

fig.subplots_adjust(hspace=0.00, wspace=0.00)

plt.show

在决定要排除或保留哪些matplotlib之前,您是否需要调用子绘图(以及所有其他matplotlib内容)?我不确定这是否是您评论的方向,但我现在有一个解决方案正在按我想要的方式工作。我基本上没有添加虚拟行和列,而是编辑了数据的打印方式。由于那一行和那一列从来都不存在,现在的情节是我想要的大小,而图例在适当的位置。是的,我在想这个。不管怎样,很高兴你的问题解决了!您提供的代码不运行。当我运行它时,一个无效的语法错误被抛出到行
gs=gridspec.gridspec(nn,nn,width\u ratios=[*[wh]*(nn-1),sm],\height\u ratios=[sm,*[wh]*(nn-1)]
,特别是
[*[wh]*(nn-1),sm]
中的第一个*。删除这两个*并运行会导致此错误:不支持+:“float”和“list”的操作数类型@mknote我使用Python 3.7和matplotlib版本3.1.1。您仍然使用Python 2.7吗?请尝试将
*[wh]*(nn-1)
更改为0.198、0.198、0.198、0.198、0.198、0.198、0.198和
*[wh]*(nn-1)
到0.198、0.198、0.198、0.198,事实上我仍然使用2.7,您提供的更正允许代码运行。输出与您的不完全相同,但非常相似,确实提供了问题的解决方案。碰巧的是,在此期间,我制定了另一个解决方案,我想我最终会使用它(我在对原始问题的评论中概述了它),但由于这确实解决了问题,我将接受这一解决方案。