首页 > 解决方案 > plt.subplot_adjust() not working correctly

问题描述

I am making some density plots like so:

import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import r2_score
import matplotlib
from scipy import stats
import matplotlib.gridspec as gridspec
from mpl_toolkits.axes_grid1.inset_locator import InsetPosition
from matplotlib.ticker import FormatStrFormatter
import matplotlib.cm as cm
from scipy.ndimage.filters import gaussian_filter
import random

matplotlib.rcParams.update({'font.size': 16})
matplotlib.rcParams['xtick.direction'] = 'in'
matplotlib.rcParams['ytick.direction'] = 'in'

x = random.sample(range(1, 10001), 1000)
y = random.sample(range(1, 10001), 1000)



def myplot(x, y, s, bins=1000):
    heatmap, xedges, yedges = np.histogram2d(x, y, bins=bins)
    heatmap = gaussian_filter(heatmap, sigma=s)

    extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
    return heatmap.T, extent
cmap = cm.YlOrRd

fig, (ax, ax1, cax) = plt.subplots(ncols = 3, figsize = (15, 5),
                       gridspec_kw={"width_ratios":[1,1, 0.5]})
img, extent = myplot(x, y, 20)
im = ax.imshow(img, extent = extent, origin = 'lower', cmap = cmap)
ax.text(0.05, 0.92, '$R^2$ = {}'.format(np.round(r2_score(x, y), 2)), fontsize=14, color = 'k', transform = ax.transAxes)
ax.plot(ax.get_xlim(), ax.get_ylim(), ls="--", c=".3")
ax.set_xlabel("Black Sky")
ax.set_ylabel("Blue Sky")

img2, extent2 = myplot(x, y, 20)
ax1.imshow(img2, extent = extent2, origin = 'lower', cmap = cmap)
ax1.text(0.05, 0.92, '$R^2$ = {}'.format(np.round(r2_score(x, y), 2)), fontsize=14, color = 'k', transform = ax1.transAxes)
ax1.axes.get_yaxis().set_visible(False)
ax1.yaxis.set_ticks([])
ax1.plot(ax1.get_xlim(), ax1.get_ylim(), ls="--", c=".3")
ax1.set_xlabel("White Sky")


ip = InsetPosition(ax1, [1.05,0,0.05,1]) 

cax.set_axes_locator(ip)

fig.colorbar(im, cax=cax, ax=[ax,ax1], use_gridspec = True)

plt.subplots_adjust(wspace=0.1, hspace=0)

which gives me a plot like this:

enter image description here

No matter what I change wspace to the plot stays the same. I think this is because when I turn of the y-axis in ax1 I am just making the text blank instead of removing the y-axis all together. Is there a way to do this so that I can make the width spacing between the figures closer together?

标签: python-3.xmatplotlib

解决方案


As commented, wspace sets the minimal distance between plots. This distance may be larger in case of equal aspect axes. Then it will depend on the figure size, figure aspect and image aspect.

A. Use automatic aspect

You may set aspect = "auto" in your imshow plots,

ax.imshow(..., aspect = "auto")

enter image description here

B. Adjust the subplot parameters

You may set the left or right subplot parameter to something smaller. E.g.

plt.subplots_adjust(wspace=0.0, hspace=0, right=0.7)

enter image description here

C. Adjust the figure size

Using a smaller figure width, which is closer to the actual image aspect will also reduce whitespace around the figure.

E.g, making the figure only 11 inches wide and using 5% padding on the right,

plt.subplots(..., figsize = (11, 5))
plt.subplots_adjust(wspace=0.0, hspace=0, right=.95)

enter image description here


推荐阅读