【发布时间】:2020-10-23 13:35:48
【问题描述】:
我正在尝试为即将发表的论文创建一个角落图,但我遇到了困难。我正在创建一个 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)
我在 Stack Overflow 上查看了许多不同的问题。两个最有希望的候选人是this one,但我发现由于大量的地块,该解决方案不太可行(坦率地说,我并没有完全理解该解决方案)。我认为this one 中的第一个答案也可能有效,因为我认为这是一个大小问题(即图形没有调整大小,因此创建一个新的子图就是创建一个与原始图形大小相同的子图),但所有这一切did 是调整整个图形的大小,所以这也不起作用。
为了提供帮助,我还会附上一张图片。我获取了上面代码的输出并对其进行了编辑以显示我想要的内容:
我应该补充一点,如果我不添加子图,则输出与我预期的一样(即大小合适),因此添加子图时会出现问题,即行fig.add_subplot(111, frameon=False, xticks=[], yticks=[], xticklabels=[], yticklabels=[]).
【问题讨论】:
-
在决定排除或保留哪些子图之前,您是否需要调用子图(以及所有其他 matplotlib 内容)?
-
我不确定这是否是您发表评论的方向,但我现在有一个可以按我想要的方式工作的解决方案。我基本上只是根本没有添加虚拟行和列,而是编辑了数据的绘制方式。由于该行和列从未存在,因此该图现在是我想要的大小,并且图例位于正确的位置。
-
是的,我就是这么想的。无论如何,很好,你的问题解决了!
标签: python-2.7 matplotlib jupyter-notebook subplot