I have a very customized subplot set up.
fig = plt.figure(figsize=(12, 10))
gs = fig.add_gridspec(nrows=2, ncols=2, width_ratios=[3, 1])
ax = fig.add_subplot(gs[:, 0])
ax3 = fig.add_subplot(gs[-1, -1])
ax4=fig.add_subplot(gs[0, 1])
This sets up 3 slots for plotting: one that takes up half the space on the left, and two smaller ones on the right. However, I only want the bottom right to actually be a plot. I want the top right to be the space where the legend for the larger plot on the left to go. I could just use the axes from ax
to do this, but that shifts the whole plotting space off. Instead I thought of trying to just create ax4
and place the ax
legend there.
lines = []
labels = []
for ax in fig.get_axes():
ln, la = ax.get_legend_handles_labels()
lines.extend(ln)
labels.extend(la)
legend = ax4.legend(lines, labels, labelspacing=0.1, loc=(-0.3,0.6), fontsize='xx-large')
fig.tight_layout()
This puts the legend exactly where I want it, but the blank figure shows up, which I don't want. Is it possible to accomplish what I want using this method? If not, what is my alternative? Picture below to better understand.
CodePudding user response:
You can use ax4.axis('off')
to make axis 4 invisible if you want to stick to your approach.
However, I don't see why you don't just skip creating axis 4 and just use fig.legend()
instead of ax.legend()
. Then the legend is placed outside the axis and you can then control the exact position just as you already did with the loc
keyword.