0

I have unwanted space between my colormap and a series of subplots that I want to align with the rows of the colormap. I tried specifying the wspace argument as 0 when creating the gridspec. I also tried different column number arguments when adding the subplots. I had guesses that there was some sort of setting for the colormap that I needed to amend but could not find anything relevant.

Minimal reproducible example:

import os, numpy, math
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from scipy import stats

#dummy data 
aa = bb = cc = [0,0.5,1]
rowkeys = []
for a in aa:
    for b in bb:
        for c in cc:
            rowkeys.append(tuple([a,b,c]))
dt = {key:{grpid:numpy.random.normal(loc=0.5,scale=0.1,size=100) for grpid in range(2)} for key in rowkeys}
            
#create plot and gridspec
width = 6.5
height = 9.0
nrows,ncols = 1,10
fig = plt.figure()
fig.set_size_inches(h=height, w=width)
fig.set_dpi(900)
gs0 = fig.add_gridspec(len(rowkeys),10,hspace=0.,wspace=0.)

#the bit on the left side
ax0 = fig.add_subplot(gs0[0:len(rowkeys),0:2])
im = ax0.imshow(numpy.array(rowkeys))
ax0.set_xticks([])
ax0.set_yticks([])
ax0.set_xticks(numpy.arange(3))
ax0.set_xticklabels(['aa','bb','cc'],rotation=90,fontsize=10)

#the bit on the right side
for i,row in enumerate(rowkeys):
    for j,grpid in enumerate(dt[row]):
        vs = dt[row][grpid]
        pdf = stats.gaussian_kde(vs)
        xs = numpy.arange(0,1.1,0.05) 
        ys = pdf(xs)
        col0,col1 = 2,6
        if j == 1:
            col0,col1 = 6,10
        axi = fig.add_subplot(gs0[i,col0:col1])
        axi.fill_between(y1=ys, x=xs)
        axi.set_xlim([0,1])
        axi.set_xticks([])
        axi.set_yticks([])
        if i == len(rowkeys)-1:
            axi.set_xticks([0.5])
            axi.set_xticklabels(['GRP'+str(j+1)],rotation=90,fontsize=10)
plt.show()

code output

gcolumbus
  • 85
  • 10
  • 1
    You can use `ax0.imshow(..., aspect='auto')` to avoid the empty space. The default `aspect='equal'` forces matplotlib to add in extra whitespace to get square cells. You might need to experiment with the widths to have the `imshow` cells more or less square again. – JohanC Dec 03 '21 at 20:21

0 Answers0