Reputation: 237
I have a 2 dimensional matrix, say img
which I want to save as in image, using the 'hot'
colormap. The following code
import matplotlib.pyplot as plt
plt.imsave("out.jpg", img, cmap = 'hot')
allows me to do this. However, I want to save the colorbar along with the image, it is important for me to know what the value at each pixel was, roughly. Let's assume that I have a lot of space available on the right.
I know that it can be done in an "easy" way, by creating a figure using plt.imshow()
, adding a colorbar using plt.colorbar()
and then saving it using plt.savefig()
, but that also saves the "grey region" around the figure and the colorbar appears separately. Also, this has issues with the figure size, in case scaling is involved. I want the colorbar to appear ON the image, and the resultant output image to be of the same size as the matrix.
Also, if anyone has any other suggestions about visualizing a matrix as an image, (where the values are not bounded), they would be appreciated.
Upvotes: 4
Views: 7577
Reputation: 2332
I'm not sure how to add a colorbar to your image before you save it like you want to, and I'm not even sure if that's possible. But I can provide you with a way to plot your image, add the colorbar, and save it, but format it the way you want. Try something like the following
import matplotlib.pyplot as plt
fig = plt.figure(figsize = (W,H)) # Your image (W)idth and (H)eight in inches
# Stretch image to full figure, removing "grey region"
plt.subplots_adjust(left = 0, right = 1, top = 1, bottom = 0)
im = plt.imshow('out.jpg') # Show the image
pos = fig.add_axes([0.93,0.1,0.02,0.35]) # Set colorbar position in fig
fig.colorbar(im, cax=pos) # Create the colorbar
plt.savefig('out.jpg')
I can't guarantee that this will work without having something to test it on, but it should be in the right direction for what you want.
Upvotes: 4