I would like to plot a number of curves over an image
Using this code I am reasonably close:
G=plt.matplotlib.gridspec.GridSpec(64,1)
fig = plt.figure()
plt.imshow(img.data[:,:],cmap='gray')
plt.axis('off')
plt.axis([0,128,0,64])
for i in arange(64):
fig.add_subplot(G[i,0])
plt.axis('off')
# note that vtc.data.shape = (64, 128*400=51200)
# so every trace for each image pixel is 400 points long
plt.plot(vtc.data[i,:])
plt.axis([0, 51200, 0, 5])
The result that I am getting looks like this:
The problem is that while I seem to be able to get rid of all the padding in the horizontal (x) direction, there is different amount of padding in the image and the stacked plots in the vertical direction.
I tried using
ax = plt.gca()
ax.autoscale_view('tight')
but that didn't reduce the margin either.
How can I get a grid of m-by-n line plots to line up precisely with a blown up (by factor f) version of an image with dimensions (fm)-by-(fn)?
UPDATE and Solution:
The answer by #RutgerKassies works quite well. I achieved it using his code like so:
fig, axs = plt.subplots(1,1,figsize=(8,4))
axs.imshow(img.data[:,:],cmap='gray', interpolation='none')
nplots = 64
fig.canvas.draw()
box = axs._position.bounds
height = box[3] / nplots
for i in arange(nplots):
tmpax = fig.add_axes([box[0], box[1] + i * height, box[2], height])
tmpax.set_axis_off()
# make sure to get image orientation right and
tmpax.plot(vtc.data[nplots-i-1,:],alpha=.3)
tmpax.set_ylim(0,5)
tmpax.set_xlim(0, 51200)
I think the easiest way is to use the boundaries from your 'imshow axes' to manually calculate the boundaries of all your 'lineplot axes':
import matplotlib.pyplot as plt
import numpy as np
fig, axs = plt.subplots(1,1,figsize=(15,10))
axs.imshow(np.random.rand(50,100) ,cmap='gray', interpolation='none', alpha=0.3)
nplots = 50
fig.canvas.draw()
box = axs._position.bounds
height = box[3] / nplots
for i in arange(nplots):
tmpax = fig.add_axes([box[0], box[1] + i * height, box[2], height])
tmpax.set_axis_off()
tmpax.plot(np.sin(np.linspace(0,np.random.randint(20,1000),1000))*0.4)
tmpax.set_ylim(-1,1)
The above code seems nice, but i do have some issues with the autoscale chopping off part of the plot. Try removing the last line to see the effect, im not sure why thats happening.
Related
I'm trying to create imshow subplots with the same pixel size without having the figure height automatically scaled, but I haven't been able to figure out how.
Ideally, I'm looking for a plot similar to the second picture, without the extra white space (ylim going from -0.5 to 4.5) and maybe centered vertically. My pictures will always have the same width, so maybe if I could fix the subplot width instead of the height that would help. Does anyone have any ideas?
close('all')
f,ax=subplots(1,2)
ax[0].imshow(random.rand(30,4),interpolation='nearest')
ax[1].imshow(random.rand(4,4),interpolation='nearest')
tight_layout()
f,ax=subplots(1,2)
ax[0].imshow(random.rand(30,4),interpolation='nearest')
ax[1].imshow(random.rand(4,4),interpolation='nearest')
ax[1].set_ylim((29.5,-0.5))
tight_layout()
Plot without ylim adjustment:
Plot with ylim adjustment:
In principle you can just make the figure size small enough in width, such that it constrains the widths of the subplots. E.g. figsize=(2,7) would work here.
For an automated solution, you may adjust the subplot parameters, such that the left and right margin constrain the subplot width. This is shown in the code below.
It assumes that there is one row of subplots, and that all images have the same pixel number in horizontal direction.
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(1,2)
im1 = ax[0].imshow(np.random.rand(30,4))
im2 = ax[1].imshow(np.random.rand(4,4))
def adjustw(images, wspace="auto"):
fig = images[0].axes.figure
if wspace=="auto":
wspace = fig.subplotpars.wspace
top = fig.subplotpars.top
bottom = fig.subplotpars.bottom
shapes = np.array([im.get_array().shape for im in images])
w,h = fig.get_size_inches()
imw = (top-bottom)*h/shapes[:,0].max()*shapes[0,1] #inch
n = len(shapes)
left = -((n+(n-1)*wspace)*imw/w - 1)/2.
right = 1.-left
fig.subplots_adjust(left=left, right=right, wspace=wspace)
adjustw([im1, im2], wspace=1)
plt.show()
If you need to use tight_layout(), do so before calling the function. Also you would then definitely need to set the only free parameter here, wspace to something other than "auto". wspace=1 means to have as much space between the plots as their width.
The result is a figure where the subplots have the same size in width.
I have specs for a mockup, for example, Photoshop/Illustrator/Sketch file with each elements specifications like size, position, and coordinates in pixels.
An image looks like:
I can draw similar image just using standard matplotlib technic without any problems.
The question is, how to render an image exactly with its specs? All sizes, font sizes, alignments, should be the same as in the specs (as it's drawn in Illustrator).
I've researched over matplotlib docs, but even transformers tutorial doesn't help.
Update with an exact example.
I have a mock at Zeplin which shows coordinated of each plot (Image is also a plot here). So I know, that the image has margins 25x25px from a border and its size is 80x80 pixels.
this is mock image (again not allowed to embed the image).
How would you do that?
The code I use for drawing
fig, ax = plt.subplots(1, 2, figsize=(20, 10), sharey=True)
recs = ax[0].barh(y_pos, widths, align='edge');
img = mpimg.imread('/Users/iwitaly/Downloads/2017-11-12 17.40.46.jpg')
ax[0].spines['left'].set_visible(False);
ax[0].spines['right'].set_visible(False);
ax[0].spines['bottom'].set_visible(False);
ax[0].spines['top'].set_visible(False);
ax[0].get_xaxis().set_visible(True);
ax[0].get_yaxis().set_visible(True);
obj = ax[0].text(x=0, y=3.9, s=r'Name: Vitaly Davydov',
fontsize=30, fontname="Courier New", weight='bold');
ax[0].axhline(y=3.85, xmin=0, xmax=0.75, color='black');
# I'd like to place axicon exactly with 25x25 marging from top left corner
axicon = fig.add_axes([0.08, 1, 0.2, 0.2], transform=None)
axicon.axis('off');
axicon.imshow(img, interpolation='none');
for i, r in enumerate(recs):
r.set_color(index_to_color[i]);
r.set_height(col_wight);
ax[0].text(x=0, y=text_positions[i], s=index_to_text[i], fontsize=30, fontname="Courier New");
ax[1].spines['left'].set_visible(False);
ax[1].spines['right'].set_visible(False);
ax[1].spines['bottom'].set_visible(False);
ax[1].spines['top'].set_visible(False);
ax[1].get_xaxis().set_visible(False);
ax[1].get_yaxis().set_visible(False);
ax[1].text(x=0, y=3.9, s='Increment:', fontsize=30,
fontname="Courier New", weight='bold');
ax[1].axhline(y=3.85, xmin=0, xmax=0.4, color='black');
for i, r in enumerate(recs):
text_x, text_y = r.xy
increment_pos_y = text_y + col_wight / 2
if increment_values[i] > 0:
increment_text = '+{}'.format(increment_values[i])
elif increment_values[i] < 0:
increment_text = '-{}'.format(increment_values[i])
else:
increment_text = '{}'.format(increment_values[i])
ax[1].text(x=0, y=increment_pos_y, s=increment_text,
fontsize=30, color=index_to_color[i],
fontname="Courier New", weight='bold');
In this example I'd like to place axicon axes that is an image with 25x25 margin and 80x80 size (all in pixels).
To place an axes to the figure, you can use fig.add_axes([left, bottom, width, height]), where left, bottom, width, height are fractions of the figure size.
To convert from pixels to fraction of figure size, you need to divide the pixels by the figure dpi and the figure size. E.g. for the left edge
left = 25/fig.dpi/fig.get_size_inches()[0]
Complete example:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(1, 2, figsize=(10, 7))
y_pos, widths = np.linspace(0,3,4), np.random.rand(4)
recs = ax[0].barh(y_pos, widths, align='edge');
#img = plt.imread('/Users/iwitaly/Downloads/2017-11-12 17.40.46.jpg')
img = np.random.rand(80,80)
# I'd like to place axicon exactly with 25x25 marging from top left corner
x,y= 25,25 #pixels
dx,dy = 80,80
w,h = fig.get_size_inches()
axicon = fig.add_axes([x/float(fig.dpi)/w, 1.-(y+dy)/float(fig.dpi)/h,
dx/float(fig.dpi)/w, dy/float(fig.dpi)/h])
axicon.axis('off');
axicon.imshow(img, interpolation='none');
plt.show()
I'm trying to write a function to automate the placement of watermark in the lower right of my figures. Here is my function so far.
from PIL import Image
import matplotlib.pyplot as plt
def watermark(fig, ax):
""" Place watermark in bottom right of figure. """
# Get the pixel dimensions of the figure
width, height = fig.get_size_inches()*fig.dpi
# Import logo and scale accordingly
img = Image.open('logo.png')
wm_width = int(width/4) # make the watermark 1/4 of the figure size
scaling = (wm_width / float(img.size[0]))
wm_height = int(float(img.size[1])*float(scaling))
img = img.resize((wm_width, wm_height), Image.ANTIALIAS)
# Place the watermark in the lower right of the figure
xpos = ax.transAxes.transform((0.7,0))[0]
ypos = ax.transAxes.transform((0.7,0))[1]
plt.figimage(img, xpos, ypos, alpha=.25, zorder=1)
The problem is that when I add a label to either axis the position of the water mark changes. E.g. adding ax.set_xlabel('x-label', rotation=45) changes the watermark position significantly. This seems to be the case because the placement of the watermark is relative to the whole figure (e.g. the plotting and axis area), however the function get_size_inches() only calculates the plotting area (e.g. not including the axis area).
Is there anyway to get the pixel dimensions of the entire figure (e.g. including axis area) or another easy workaround.
Thanks in advance.
You may want to use an AnchoredOffsetbox in which you place an OffsetImage. The advantage would be that you can use the loc=4 argument to place the Offsetbox in the lower right corner of the axes (just like in the case of a legend).
from PIL import Image
import matplotlib.pyplot as plt
from matplotlib.offsetbox import ( OffsetImage,AnchoredOffsetbox)
def watermark2(ax):
img = Image.open('house.png')
width, height = ax.figure.get_size_inches()*fig.dpi
wm_width = int(width/4) # make the watermark 1/4 of the figure size
scaling = (wm_width / float(img.size[0]))
wm_height = int(float(img.size[1])*float(scaling))
img = img.resize((wm_width, wm_height), Image.ANTIALIAS)
imagebox = OffsetImage(img, zoom=1, alpha=0.2)
imagebox.image.axes = ax
ao = AnchoredOffsetbox(4, pad=0.01, borderpad=0, child=imagebox)
ao.patch.set_alpha(0)
ax.add_artist(ao)
fig, ax = plt.subplots()
ax.plot([1,2,3,4], [1,3,4.5,5])
watermark2(ax)
ax.set_xlabel("some xlabel")
plt.show()
I have the following function:
def get_rgba_bitmap(fig):
fig.canvas.draw()
tab = fig.canvas.copy_from_bbox(fig.bbox).to_string_argb()
ncols, nrows = fig.canvas.get_width_height()
return numpy.fromstring(tab, dtype = numpy.uint8).reshape(nrows, ncols, 4)
With this function I am able to create a "map" of an image. See link for more details on why I need the "map" and the answer resulting in the function. Plotting the "map" gives:
import numpy
import matplotlib.pyplot as plt
random_gen = numpy.random.mtrand.RandomState(seed = 127260)
x_test = random_gen.uniform(-1., 1., size= (10,10))
fig1 = plt.figure()
ax1 = fig1.add_subplot(1, 1, 1)
ax1.imshow(x_test, cmap = "seismic")
bitmap_rgba1 = get_rgba_bitmap(fig1)
fig2 = plt.figure()
ax1 = fig2.add_subplot(1, 1, 1)
ax1.imshow(bitmap_rgba1)
plt.show()
The canvas that is created with get_rgba_bitmap(fig) is of the entire figure including the grey background. When plotting the "map", the grey background is thus also included, shrinking the size of the actual image. In the case of a single image this does not matter to me as there is a way to work around it. However, I now need several subplots and it does become a problem.
Therefore, what I now need is a function that creates a canvas of only the plotting frame. Ticks and labels are not important. I tried modifying the get_rgba_bitmap function but it does not fully work:
def test(fig, ax):
fig.canvas.draw()
tab = fig.canvas.copy_from_bbox(ax.bbox).to_string_argb()
bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
width, height = bbox.width * fig.dpi, bbox.height * fig.dpi
ncols, nrows = width, height
return numpy.fromstring(tab, dtype = numpy.uint8).reshape(nrows + 1, ncols + 1, 4)
I think the problem lies in wrong values for ncols and nrows. Not sure where this comes from.
If I add 1 to both ncols and nrows in reshape, the script runs and produces an image close to what I want. However, the "map" does not fit correctly in the new plotting frame, which from the look of it is off by 1 pixel in x and y. This corresponds to the 1 I needed to add to nrows and ncols. How can I fix this?
Thank you for help
I am stuck in a rather complicated situation. I am plotting some data as an image with imshow(). Unfortunately my script is long and a little messy, so it is difficult to make a working example, but I am showing the key steps. This is how I get the data for my image from a bigger array, written in a file:
data = np.tril(np.loadtxt('IC-heatmap-20K.mtx'), 1)
#
#Here goes lot's of other stuff, where I define start and end
#
chrdata = data[start:end, start:end]
chrdata = ndimage.rotate(chrdata, 45, order=0, reshape=True,
prefilter=False, cval=0)
ax1 = host_subplot(111)
#I don't really need host_subplot() in this case, I could use something more common;
#It is just divider.append_axes("bottom", ...) is really convenient.
plt.imshow(chrdata, origin='lower', interpolation='none',
extent=[0, length*resolution, 0, length*resolution]) #resolution=20000
So the values I am interested in are all in a triangle with the top angle in the middle of the top side of a square. At the same time I plot some data (lot's of coloured lines in this case) along with the image near it's bottom.
So at first this looks OK, but is actually is not: all pixels in the image are not square, but elongated with their height being bigger, than their width. This is how they look if I zoom in:
This doesn't happen, If I don't set extent when calling imshow(), but I need it so that coordinates in the image and other plots (coloured lines at the bottom in this case), where identical (see Converting coordinates of a picture in matplotlib?).
I tried to fix it using aspect. I tried to do that and it fixed the pixels' shape, but I got a really weird picture:
The thing is, later in the code I explicitly set this:
ax1.set_ylim(0*resolution, length*resolution) #resolution=20000
But after setting aspect I get absolutely different y limits. And the worst thing: ax1 is now wider, than axes of another plot at the bottom, so that their coordinates do not match anymore! I add it in this way:
axPlotx = divider.append_axes("bottom", size=0.1, pad=0, sharex=ax1)
I would really appreciate help with getting it fixed: square pixels, identical coordinates in two (or more, in other cases) plots. As I see it, the axes of the image need to become wider (as aspect does), the ylims should apply and the width of the second axes should be identical to the image's.
Thanks for reading this probably unclear explanation, please, let me know, if I should clarify anything.
UPDATE
As suggested in the comments, I tried to use
ax1.set(adjustable='box-forced')
And it did help with the image itself, but it caused two axes to get separated by white space. Is there any way to keep them close to each other?
Re-edited my entire answer as I found the solution to your problem. I solved it using the set_adjustable("box_forced") option as suggested by the comment of tcaswell.
import numpy
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot, make_axes_locatable
#Calculate aspect ratio
def determine_aspect(shape, extent):
dx = (extent[1] - extent[0]) / float(shape[1])
dy = (extent[3] - extent[2]) / float(shape[0])
return dx / dy
data = numpy.random.random((30,60))
shape = data.shape
extent = [-10, 10, -20, 20]
x_size, y_size = 6, 6
fig = plt.figure(figsize = (x_size, y_size))
ax = host_subplot(1, 1, 1)
ax.imshow(data, extent = extent, interpolation = "None", aspect = determine_aspect(shape, extent))
#Determine width and height of the subplot frame
bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
width, height = bbox.width, bbox.height
#Calculate distance, the second plot needs to be elevated by
padding = (y_size - (height - width)) / float(1 / (2. * determine_aspect(shape, extent)))
#Create second image in subplot with shared x-axis
divider = make_axes_locatable(ax)
axPlotx = divider.append_axes("bottom", size = 0.1, pad = -padding, sharex = ax)
#Turn off yticks for axPlotx and xticks for ax
axPlotx.set_yticks([])
plt.setp(ax.get_xticklabels(), visible=False)
#Make the plot obey the frame
ax.set_adjustable("box-forced")
fig.savefig("test.png", dpi=300, bbox_inches = "tight")
plt.show()
This results in the following image where the x-axis is shared:
Hope that helps!