1

In the figure below (1) there is a lot of white space around the hexagonal grid that I cannot figure out how to remove. I've tried different methods i.e. tight_layout etc.

SOM Hitmap

The code is

import matplotlib.pyplot as plt
from matplotlib.patches import RegularPolygon
import matplotlib.cm as cm
import matplotlib.colors as colors
import numpy

def plot_som_hm(hm,colormap,a=1):
    # setup hexagon offsets
    m,n = hm.shape
    offsety = .75 * 2*a
    offsetx = numpy.sqrt(3) * a
    evenrow = numpy.sqrt(3)/2 * a

    # set up the figure
    fig,ax = plt.subplots(figsize=(2,2))
    ax.set_aspect('equal')

    # define colormap
    cmap = cm.ScalarMappable(None,colormap)
    norm = colors.Normalize(vmin=hm.min(),vmax=hm.max())

    # iterate over the hitmap, drawing a hexagon 
    xs = []
    ys = []
    for i in range(m):
        for j in range(n):
            # calculate center point for current hexagonal grid & draw it
            offsetr = evenrow if i % 2 == 0 else 0
            x,y = (j*offsetx+offsetr,-i*offsety)
            hexg = RegularPolygon(
                (x,y),numVertices=6,radius=a,facecolor=cmap.cmap(norm(hm[i][j]))
            )
            ax.add_patch(hexg)
            xs.append(x)
            ys.append(y)

    # add a scatter plot so all hexagons show up & turn off ticks
    ax.scatter(xs,ys,alpha=1.0)
    ax.set_xticks([])
    ax.set_yticks([])

    # add a colorbar
    sm = plt.cm.ScalarMappable(cmap=colormap,norm=norm)
    sm._A = []
    plt.colorbar(sm,ticks=range(int(hm.min()),int(hm.max())+1))

    # and show the hitmap
    plt.show()

which can be called by plot_som_hm(hitmap,'inferno',-0.5)

I am not sure if the whitespace is the result of calling subplots (figsize=(2,2)) or something else. Being relatively new to matplotlib I am not sure where the whitespace is coming from i.e. if it is the figure, the axis or even the plt so searching on Google has not provided any relevant answers.

Ali AzG
  • 1,861
  • 2
  • 18
  • 28
  • Which whitespace are you referring to? between the hexagons and the black border, or outside the black border? – Dinari Nov 17 '18 at 14:00

1 Answers1

1

II suggest to read the x- and y-limits to see how you can adjust them to your needs, i.e.:

print(ax.get_xlim())

and then e.g.

ax.set_xlim(0.5, 5.5)

or whatever fits.

The same then with the y-axis.

SpghttCd
  • 10,510
  • 2
  • 20
  • 25