Open saved png's by savefig to plot them in subplots - python

I saved plots with savefig like plt.savefig('1.png') and now I want to adjust them to determined subplots like:
import matplotlib.pyplot as plt
from PIL import Image
img1 = Image.open("1.png")
img1 = Image.open("2.png")
img1 = Image.open("3.png")
fig, (ax_1, ax_2, ax_3) = plt.subplots(nrows=3, ncols=1,
sharex=True, figsize=(8.27,11.7))
ax_1.set_title('Plot1')
ax_1 = img1
ax_2.set_title('Plot2')
ax_2 = img2
ax_3.set_title('Plot3')
ax_3 = img3
fig.suptitle('Name')
plt.show()
But I get 3 empty plots without an error

Use ax.imshow():
import matplotlib.pyplot as plt
from PIL import Image
img1 = Image.open("1.png")
img1 = Image.open("2.png")
img1 = Image.open("3.png")
fig, (ax_1, ax_2, ax_3) = plt.subplots(nrows=3, ncols=1,
sharex=True, figsize=(8.27,11.7))
ax_1.set_title('Plot1')
ax_1.imshow(img1)
ax_2.set_title('Plot2')
ax_2.imshow(img2)
ax_3.set_title('Plot3')
ax_3.imshow(img3)
fig.suptitle('Name')
plt.show()
If you want to remove the ticks and tick labels, you can add ax.axis('off') for every axis you to remove them.

Related

plotting a grid of png with matplotlib

I have found multiple similar questions with this subject but so far I couldn't adapt any solution to my needs, so I'm sorry for reposting.
I'm trying to plot a grid of png images using matplotlib, the closest I've got to what I want is using the code below, which can be found here https://matplotlib.org/stable/gallery/axes_grid1/simple_axesgrid.html .
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np
im1 = np.arange(100).reshape((10, 10))
im2 = im1.T
im3 = np.flipud(im1)
im4 = np.fliplr(im2)
fig = plt.figure(figsize=(4., 4.))
grid = ImageGrid(fig, 111, # similar to subplot(111)
nrows_ncols=(2, 2), # creates 2x2 grid of axes
axes_pad=0.1, # pad between axes in inch.
)
for ax, im in zip(grid, [im1, im2, im3, im4]):
# Iterating over the grid returns the Axes.
ax.imshow(im)
plt.show()
My question is, how do I get rid of the x and y ticks/labels and also give each image a title?
Again, I'm sorry for repeating the question.
This code
import matplotlib.pyplot as plt
image = plt.imread("sample.png")
fig, axes = plt.subplots(2, 3)
for row in [0, 1]:
for column in [0, 1, 2]:
ax = axes[row, column]
ax.set_title(f"Image ({row}, {column})")
ax.axis('off')
ax.imshow(image)
plt.show()
is going to produce

Plotting two images in Matplotlib on the same axes

I'm trying to plot two images on the same axes. Here is the code I'm experimenting with (I'm new to MatplotLib - so apologies in advance)...
import matplotlib.pyplot as plt
from matplotlib import transforms
img = plt.imread('image1.gif')
fig = plt.figure()
ax = fig.add_subplot(111)
rotation_in_degrees = 60
tr = transforms.Affine2D().rotate_deg(rotation_in_degrees)
ax.imshow(img)
ax.imshow(img, transform=tr)
plt.show()
There are two issues. Firstly, only the first image appears in the display; the second is only partially shown. Is there a way to show the two images in the same plot? That is, the axes are automatically scaled.
Secondly, as you can see, I'm trying to rotate the image but I'm sure that I'm not doing correctly in the sense I don't know if I'm rotating it around the origin of the plot etc. Any advice or links for other posts would be great!
Thanks for you help in advance.
To solve your firs problem - you need to display each image in separate subplot, now - you are plotting in the same subplot. See example of plotting in separate plots:
import matplotlib.pyplot as plt
from matplotlib import transforms
img = plt.imread('image.gif')
fig = plt.figure()
rotation_in_degrees = 60
tr = transforms.Affine2D().rotate_deg(rotation_in_degrees)
ax = fig.add_subplot(121)
ax.imshow(img)
ax = fig.add_subplot(122)
ax.imshow(img)
plt.show()
For the second issue with rotation - I would use PIL:
from PIL import Image
import matplotlib.pyplot as plt
img = Image.open('image.gif')
fig = plt.figure()
rotation_in_degrees = 60
ax = fig.add_subplot(121)
ax.imshow(img)
img2 = img.rotate(rotation_in_degrees)
ax = fig.add_subplot(122)
ax.imshow(img2)
plt.show()

Adjust size of 2 contour maps to height of color bar [duplicate]

I use the following code to generate side-by-size images and I need to add colorbar only to the second image in the row. I use the following code for it
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.gridspec as gridspec
def plotting(x):
gs1 = gridspec.GridSpec(1, 2)
gs1.update(wspace=0.005, hspace=0.005)
plt.subplot(gs1[0])
plt.imshow(x)
plt.axis('off')
plt.title('dog')
ax1 = plt.subplot(gs1[1])
imc = plt.imshow(x, cmap='hot', interpolation='nearest')
plt.axis('off')
plt.title('dog')
divider = make_axes_locatable(ax1)
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(imc, cax=cax)
plt.tight_layout()
plt.show()
However it comes out the size of side-by-side images are not equal. I wonder how I could fix this issue?
You can use ImageGrid, which was created exactly for this purpose:
from mpl_toolkits.axes_grid1 import ImageGrid
x = np.random.random(size=(10,10))
fig = plt.figure()
grid = ImageGrid(fig, 111,
nrows_ncols = (1,2),
axes_pad = 0.05,
cbar_location = "right",
cbar_mode="single",
cbar_size="5%",
cbar_pad=0.05
)
grid[0].imshow(x)
grid[0].axis('off')
grid[0].set_title('dog')
imc = grid[1].imshow(x, cmap='hot', interpolation='nearest')
grid[1].axis('off')
grid[1].set_title('dog')
plt.colorbar(imc, cax=grid.cbar_axes[0])

Colorbar sticking to axes

I've got a small problem with the positioning of a colorbar using matplotlib. I'm plotting several subplots and one of them is an image. I want this image to have a colorbar but I want it to be "stuck" to the figure, so that there is no space between the two axes (the one from the figure and the one from the colorbar). Even if the figure is resized, the colorbar should always stick to the image axes.
PS - I don't mind if ax3 (the axes of my image) is deformed.
Here's what I've got for the moment:
# Imports
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from scipy import *
# Generating data
data = (rand(2048,2048), rand(2048,2048)+1000)
colorplot = "blue"
metadata = ("Test1", "Test2", "spectral")
# Generating figure and subplots
fig = plt.figure()
fig.subplots_adjust(right = 0.8)
gs1 = gridspec.GridSpec(3, 5)
gs1.update(left=0.05,\
right=0.95,\
top=0.95,\
bottom=0.05,\
wspace=0.2,\
hspace=0.05)
ax1 = fig.add_subplot(gs1[0,0])
ax2 = fig.add_subplot(gs1[0,1])
ax3 = fig.add_subplot(gs1[1:3,0:2])
ax4 = fig.add_subplot(gs1[:,2:])
list_axes = [ax1, ax2, ax3, ax4]
for i in list_axes:
i.autoscale_view(tight=False, scalex=False, scaley=True)
# Misc computation
array = data[1]-data[0]
mean_value = np.mean(array)
std_value = np.std(array)
nb_sigma = 5
ax1.imshow(data[0], interpolation = "nearest", cmap = metadata[2])
ax2.imshow(data[1], interpolation = "nearest", cmap = metadata[2])
im = ax3.imshow(array, vmin = np.min(array[array>mean_value-nb_sigma*std_value]), vmax = np.max(array[array<mean_value+nb_sigma*std_value]), interpolation = "nearest", cmap = metadata[2])
ax3.set_adjustable('box-forced')
# Creating axes for the colorbar
axes_cb = fig.add_axes([ax3.get_position().bounds[0],ax3.get_position().bounds[1], ax3.get_position().bounds[2], 0.05])
fig.colorbar(im, cax = axes_cb, orientation = 'horizontal')
axes_cb.yaxis.tick_left()
n, bins, patches = ax4.hist(array.flatten(), color = colorplot, bins = 50, normed = True)
plt.show()
Thank you!

Grid of images in matplotlib with no padding

I'm trying to make a grid of images in matplotlib using gridspec. The problem is, I can't seem to get it to get rid of the padding between the rows.
Here's my attempt at the solution.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np
from os import listdir
from os import chdir
from PIL import Image
import matplotlib.gridspec as gridspec
chdir('/home/matthew/Dropbox/Work/writing/'+
'paper_preperation/jump_figs')
files = listdir('/home/matthew/Dropbox/Work/writing/'+
'paper_preperation/jump_figs')
images = [Image.open(f) for f in files]
"""
fig = plt.figure()
grid = ImageGrid(fig, 111, # similar to subplot(111)
nrows_ncols = (2, 5), # creates 2x2 grid of axes
axes_pad=0.1, # pad between axes in inch.
)
"""
num_rows = 2
num_cols = 5
fig = plt.figure()
gs = gridspec.GridSpec(num_rows, num_cols, wspace=0.0)
ax = [plt.subplot(gs[i]) for i in range(num_rows*num_cols)]
gs.update(hspace=0)
#gs.tight_layout(fig, h_pad=0,w_pad=0)
for i,im in enumerate(images):
ax[i].imshow(im)
ax[i].axis('off')
#ax_grid[i/num_cols,i-(i/num_cols)*num_cols].imshow(im) # The AxesGrid object work as a list of axes.
#ax_grid[i/num_cols,i-(i/num_cols)*num_cols].axis('off')
"""
all_axes = fig.get_axes()
for ax in all_axes:
for sp in ax.spines.values():
sp.set_visible(False)
if ax.is_first_row():
ax.spines['top'].set_visible(True)
if ax.is_last_row():
ax.spines['bottom'].set_visible(True)
if ax.is_first_col():
ax.spines['left'].set_visible(True)
if ax.is_last_col():
ax.spines['right'].set_visible(True)
"""
plt.show()
Also does anyone know how to make each subplot bigger?
For me a combination of aspect="auto" and subplots_adjust worked. Also I always try to make the subplots quadratic. For the individual subplot size figsize can be adjusted.
fig, axes = plt.subplots(nrows=max_rows, ncols=max_cols, figsize=(20,20))
for idx, image in enumerate(images):
row = idx // max_cols
col = idx % max_cols
axes[row, col].axis("off")
axes[row, col].imshow(image, cmap="gray", aspect="auto")
plt.subplots_adjust(wspace=.05, hspace=.05)
plt.show()

Categories