MyCarta MyCarta - 1 month ago 7
Python Question

Overlapping text when saving multiple Matplotlib images with text in a loop

I created this randomly-valued/coloured 'chessboard':

chessboard

with the code:

rndm = np.random.rand(8,8)
my_cmap = plt.get_cmap('gray')

plt.figure(figsize=(5,4))
plt.imshow(rndm, cmap=my_cmap, interpolation = 'none')
plt.axis('off')
plt.show()


I wanted to apply a function to the values in a loop, for example raising all values in the array to an increasing power, and then show all in different subplots. Here's the code:

fig, axs = plt.subplots(2,2, figsize=(10, 10))
axs = axs.ravel()

for i, n in zip(np.arange(4), np.arange(2,6)):
axs[i].imshow(np.power(rndm, n), cmap=my_cmap, interpolation = 'none')
axs[i].axis('off')
axs[i].text(1, 1, str(n), fontsize=14, color = 'y')


and the result:

subplots

But what I would really like is to cycle through 4 colormaps, for example:

cmaps = ['viridis', 'inferno', 'plasma', 'magma']
fig, axs = plt.subplots(2,2, figsize=(10, 10))
axs = axs.ravel()

for i, n in zip(np.arange(4), np.arange(2,6)):
axs[i].imshow(np.power(rndm, n), cmap=cmaps[i], interpolation = 'none')
axs[i].axis('off')
axs[i].text(1, 1, str(n), fontsize=14, color = 'y')


coloured subplots

Good. But here's where my code breaks. I want to save these as individual images.
I wrote this, which is fine except for the fact that the text numbers end up superimposed:

for i, n in zip(np.arange(4), np.arange(2,6)):
plt.imshow(np.power(rndm, n), cmap=cmaps[i], interpolation = 'none')
plt.axis('off')
plt.text(1, 1, str(n), fontsize=14, color = 'y')
plt.savefig("test_n = " + str(n) +".png", dpi=300, bbox_inches='tight', pad_inches=0)


enter image description here

How do I clear them each time?

Answer

Shouldn't you use cmaps[i] instead of cmap=my_cmap? Create a figure in each loop using plt.figure() and it'll work correctly (tested).

for i, n in zip(np.arange(4), np.arange(2,6)):
    plt.figure()
    plt.imshow(np.power(rndm, n), cmap=cmaps[i], interpolation = 'none')
    plt.axis('off')
    plt.text(1, 1, str(n), fontsize=14, color = 'y')
    plt.savefig("test_n = " + str(n) +".png", dpi=300, bbox_inches='tight', pad_inches=0)

result:

  • The main image (not saved) : enter image description here

-Saved images:

enter image description here enter image description here enter image description here enter image description here

Note that the labels starts from 2 because of this line :

plt.text(1, 1, str(n), fontsize=14, color = 'y')

If you want it start from 1 , change str(n) to str(i).