I'm trying to use matplotlib to create a 2D density plot of a distribution to use as a heightmap. Here's what I've got:
%matplotlib inline
import matplotlib.pyplot as plt
from scipy.stats import kde
import numpy as np
# make fake data
data = np.random.multivariate_normal([0, 0], [[1, 0.5], [0.5, 3]], 200)
x, y = data.T
# kde
nbins = 100
k = kde.gaussian_kde(data.T)
xi, yi = np.mgrid[x.min():x.max():nbins*1j, y.min():y.max():nbins*1j]
zi = k(np.vstack([xi.flatten(), yi.flatten()]))
# plot
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(5,5))
plt.pcolormesh(xi, yi, zi.reshape(xi.shape), shading='gouraud', cmap=plt.cm.gray)
plt.tight_layout()
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.axis('off')
plt.savefig('heightmap.png', bbox_inches = 'tight', pad_inches = 0)
This produces the following image (the data is random each run of course):
If you download that image file or change the CSS of the stackoverflow page background, you'll see that image has a little white border surrounding it. I thought I could use a hack to remove that white border by changing the background color to a fixed color with fig.patch.set_facecolor('orange')
but that doesn't work.
Does anyone know what I can do to remove the white border from the edge of the saved image? I'd be grateful for any insights others can offer!