我正在像这样绘制一些密度图:
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)
这给了我这样的情节:
无论我将wspace
更改为何种情节,都保持不变。我认为这是因为当我在ax1
中旋转y轴时,我只是将文本设置为空白,而不是一起删除y轴。有没有一种方法可以使图形之间的宽度间距更接近?
答案 0 :(得分:2)
如前所述,wspace
设置图之间的最小距离。在长宽比轴相等的情况下,此距离可能更大。然后将取决于图形大小,图形外观和图像外观。
您可以在aspect = "auto"
图中设置imshow
ax.imshow(..., aspect = "auto")
您可以将left或right子图参数设置为较小的值。例如
plt.subplots_adjust(wspace=0.0, hspace=0, right=0.7)
使用较小的图形宽度(更接近实际的图像宽高比)也会减少图形周围的空白。
例如,使图形仅宽11英寸,并在右侧使用5%的填充,
plt.subplots(..., figsize = (11, 5))
plt.subplots_adjust(wspace=0.0, hspace=0, right=.95)