I'm using bokeh 1.0.1 version inside a Django application and I would like to display microscopic surface images as zoomable image plots with a color-encoded height and colorbar. In principle this works, but I have problems to get plots with the correct aspect ratio only showing the image without space around.
Here is an example for what I want to achieve: The resulting plot should
show an image of random data having a width of sx=10 and a height of sy=5 in data space (image size)
have axes limited to (0,sx) and (0,sy), on initial view
and when zooming
a square on the screen should match a square in data space, at least in initial view
For the image I just use random data with nx=100 points in x direction and ny=100 points in y direction.
Here is my first approach:
Attempt 1
from bokeh.models.ranges import Range1d
from bokeh.plotting import figure, show
from bokeh.models import LinearColorMapper, ColorBar
import numpy as np
sx = 10
sy = 5
nx = 100
ny = 100
arr = np.random.rand(nx, ny)
x_range = Range1d(start=0, end=sx, bounds=(0,sx))
y_range = Range1d(start=0, end=sy, bounds=(0,sy))
# Attempt 1
plot = figure(x_range=x_range, y_range=y_range, match_aspect=True)
# Attempt 2
# plot = figure(match_aspect=True)
# Attempt 3
# pw = 400
# ph = int(400/sx*sy)
# plot = figure(plot_width=pw, plot_height=ph,
# x_range=x_range, y_range=y_range, match_aspect=True)
color_mapper = LinearColorMapper(palette="Viridis256",
low=arr.min(), high=arr.max())
colorbar = ColorBar(color_mapper=color_mapper, location=(0,0))
plot.image([arr], x=[0], y=[0], dw=[sx], dh=[sy],
color_mapper=color_mapper)
plot.rect(x=[0,sx,sx,0,sx/2], y=[0,0,sy,sy,sy/2],
height=1, width=1, color='blue')
plot.add_layout(colorbar, 'right')
show(plot)
I've also added blue squares to the plot in order to see, when the
aspect ratio requirement fails.
Unfortunately, in the resulting picture, the square is no square any more, it's twice as high as wide. Zooming and panning works as expected.
Attempt 2
When leaving out the ranges by using
plot = figure(match_aspect=True)
I'll get this picture. The square is a square on the screen,
this is fine, but the axis ranges changed, so there is
now space around it. I would like to have only the data area covered by the
image.
Attempt 3
Alternatively, when providing a plot_height and plot_width to the figure,
with a pre-defined aspect ratio e.g. by
pw = 800 # plot width
ph = int(pw/sx*sy)
plot = figure(plot_width=pw, plot_height=ph,
x_range=x_range, y_range=y_range,
match_aspect=True)
I'll get this picture. The square is also not a square any more. It can be done almost, but it's difficult, because the plot_width also comprises the colorbar and the toolbar.
I've read this corresponding blog post
and the corresponding bokeh documentation, but I cannot get it working.
Does anybody know how to achieve what I want or whether it is impossible?
Responsive behaviour would also be nice, but we can neglect that for now.
Thanks for any hint.
Update
After a conversation with a Bokeh developer on Gitter (thanks Bryan!) it seems that it is nearly impossible what I want.
The reason is, how match_aspect=True works in order to make a square in data space look like a square in pixel space: Given a canvas size, which may result from applying different sizing_mode settings for responsive behaviour, the data range is then changed in order to have the matching aspect ratio. So there is no other way to make the pixel aspect ratio to match the data aspect ratio without adding extra space around the image, i.e. to extend the axes over the given bounds. Also see the comment of this issue.
Going without responsive behaviour and then fixing the canvas size beforehand with respect to the aspect ratio could be done, but currently not perfectly because of all the other elements around the inner plot frame which also take space. There is a PR which may allow a direct control of inner frame dimensions, but I'm not sure how to do it.
Okay, what if I give up the goal to have tight axes?
This is done in "Attempt 2" above, but there is too much empty space around the image, the same space that the image plot takes.
I've tried to use various range_padding* attributes, e.g.
x_range = DataRange1d(range_padding=10, range_padding_units='percent')
y_range = DataRange1d(range_padding=10, range_padding_units='percent')
but it doesn't reduce the amount of space around the plot, but increases it only. The padding in percent should be relative to the image dimensions given by dh and dw.
Does anybody know how to use the range_padding parameters to have smaller axis ranges or another way to have smaller paddings around the image plot in the example above (using match_aspect=True)?
I've opened another question on this.
Can you accept this solution (works with Bokeh v1.0.4) ?
from bokeh.models.ranges import Range1d
from bokeh.plotting import figure, show
from bokeh.layouts import Row
from bokeh.models import LinearColorMapper, ColorBar
import numpy as np
sx = 10
sy = 5
nx = 100
ny = 100
arr = np.random.rand(nx, ny)
x_range = Range1d(start = 0, end = sx, bounds = (0, sx))
y_range = Range1d(start = 0, end = sy, bounds = (0, sy))
pw = 400
ph = pw * sy / sx
plot = figure(plot_width = pw, plot_height = ph,
x_range = x_range, y_range = y_range, match_aspect = True)
color_mapper = LinearColorMapper(palette = "Viridis256",
low = arr.min(), high = arr.max())
plot.image([arr], x = [0], y = [0], dw = [sx], dh = [sy], color_mapper = color_mapper)
plot.rect(x = [0, sx, sx, 0, sx / 2], y = [0, 0, sy, sy, sy / 2], height = 1, width = 1, color = 'blue')
colorbar_plot = figure(plot_height = ph, plot_width = 69, x_axis_location = None, y_axis_location = None, title = None, tools = '', toolbar_location = None)
colorbar = ColorBar(color_mapper = color_mapper, location = (0, 0))
colorbar_plot.add_layout(colorbar, 'left')
show(Row(plot, colorbar_plot))
Result:
Related
I would like to annotate a scatterplot with images corresponding to each datapoint. With standard parameters the images end up clashing with each other and other important features such as legend axis, etc. Thus, I would like the images to form a circle or a rectangle around the main scatter plot.
My code looks like this for now and I am struggling to modify it to organise the images around the center point of the plot.
import matplotlib.cbook as cbook
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import seaborn as sns
#Generate n points around a 2d circle
def generate_circle_points(n, centre_x, center_y, radius=1):
"""Generate n points around a circle.
Args:
n (int): Number of points to generate.
centre_x (float): x-coordinate of circle centre.
center_y (float): y-coordinate of circle centre.
radius (float): Radius of circle.
Returns:
list: List of points.
"""
points = []
for i in range(n):
angle = 2 * np.pi * i / n
x = centre_x + radius * np.cos(angle)
y = center_y + radius * np.sin(angle)
points.append([x, y])
return points
fig, ax = plt.subplots(1, 1, figsize=(7.5, 7.5))
data = pd.DataFrame(data={'x': np.random.uniform(0.5, 2.5, 20),
'y': np.random.uniform(10000, 50000, 20)})
with cbook.get_sample_data('grace_hopper.jpg') as image_file:
image = plt.imread(image_file)
# Set logarithmic scale for x and y axis
ax.set(xscale="log", yscale='log')
# Add grid
ax.grid(True, which='major', ls="--", c='gray')
coordianates = generate_circle_points(n=len(data),
centre_x=0, center_y=0, radius=10)
# Plot the scatter plot
scatter = sns.scatterplot(data=data, x='x', y='y', ax=ax)
for index, row in data.iterrows():
imagebox = OffsetImage(image, zoom=0.05)
imagebox.image.axes = ax
xy = np.array([row['x'], row['y']])
xybox = np.array(coordianates[index])
ab = AnnotationBbox(imagebox, xy,
xycoords='data',
boxcoords="offset points",
xybox=xybox,
pad=0)
ax.add_artist(ab)
for the moment the output looks like this:enter image description here
Ideally I would like the output to look to something like this:
enter image description here
Many thanks in advance for your help
Not an answer but a long comment:
You can control the location of the arrows, but sometimes it is easier to export figures as SVGs and edit them in Adobe Illustrator or Inkscape.
R has a dodge argument which is really nice, but even then is not always perfect. Solutions in Python exist but are laborious.
The major issue is that this needs to be done last as alternations to the plot would make it problematic. A few points need mentioning.
Your figures will have to have a fixed size (57mm / 121mm / 184mm for Science, 83mm / 171mm for RSC, 83mm / 178mm for ACS etc.), if you need to scale the figure in Illustrator keep note of the scaling factor, adding it as a textbox outside of the canvas —as the underlying plot will need to be replaced at least once due to Murphy's law. Exporting at the right size the SVG is ideal. Sounds silly, but it helps. Likewise, make sure the font size does not go under the minimum spec (7-9 points).
I am trying to make an image with multiple subplots using matplotlib. That part is no problem. What I have been struggling with is alignment. Specifically, having the outside edges of the plots aligned and having equal spacing between the plots (the same space horizontally and vertically).
I have been able to get it working with no spacing between plots:
import numpy as np
import matplotlib.pyplot as plt
plt.set_cmap('jet')
plt.close()
dim1 = 81
dim2 = 445
rad = 10
arr1 = np.random.rand(dim1, dim2) # Representative data, first plot
arr1[round(dim1/2 - rad):round(dim1/2 + rad), round(dim1/2 - rad):round(dim1/2 + rad)] += 6
arr1[round(dim1/2 - rad):round(dim1/2 + rad), round(-dim1/2 - rad):round(-dim1/2 + rad)] += 3
arr2 = arr1[:, :dim1] # Second plot
arr3 = arr1[:, -dim1:] # Third plot
xpix = dim2 # sudo x pixels in the image
ypix = xpix/2 + dim1 # sudo y pixels for the image
ratio = xpix/ypix # ratio of the width to height for the image
size = 7
fig = plt.figure(figsize = (size*ratio, size))
grid = plt.GridSpec(2, 2, wspace = 0, hspace = 0, left = 0, right = 1, top = 1, bottom = 0, height_ratios = [dim1, xpix/2])
ax1=fig.add_subplot(grid[0,:]) # Top plot
ax1.axis(False)
#ax1.set_anchor('N')
ax1.imshow(arr1, aspect = 'equal')
ax2=fig.add_subplot(grid[1,0]) # Bottom left plot
ax2.axis(False)
ax2.set_anchor('SW')
ax2.imshow(arr2, aspect = 'equal')
ax3=fig.add_subplot(grid[1,1]) # Bottom right plot
ax3.axis(False)
ax3.set_anchor('SE')
ax3.imshow(arr3, aspect = 'equal')
plt.show()
Which gives me the attached output.
No spacing plot
However, after many attempts at adding in spaces, I have had no luck. One way that I tried to do it was replacing the GridSpec line above with:
space = 0.01
grid = plt.GridSpec(2, 2, wspace = space, hspace = space*ratio, left = 0, right = 1, top = 1, bottom = 0, height_ratios=[dim1, xpix*(1-space)/2])
Sometimes depending on the space, image size, or number of pixels this seems to work, but a lot of the time it does not. I have tried several other things including using a 3*3 GridSpec with wspace = 0, hspace = 0 and using the middle row/column for spacing. I also tried using multiple GridSpec's and specifying the top, bottom, left, and right for each to get equal spacing and aligned edges. All of these attempts yielded similar results. One other important thing is that the I do need to have square pixels for each of the arrays (I noticed that a lot of the examples/other questions regarding GridSpec use subplots with nothing in them and it looks like the aspect ratio changes to get alignment?).
My ultimate goal is to be able to set an arbitrary space, size and input arrays and not have to worry about fiddling with things in order to get equal spacing with the edges aligned. Thank you in advance for any help!
Edit:
I am hoping that in the end the output will look like this: Desired Output and that I will be able to choose the amount of space between the images.
I am plotting a dotplot( here is a brief explanation of what it is)https://en.wikipedia.org/wiki/Dot_plot_(bioinformatics) of a large amount of data( the largest one being 66x80,000x80,000!!).
The current method I'm using is to plot a matplotlib scatter plot with the x,y coordinates of the dots.
the problem is I can not set the interpolation value of the plot, and the output is not a vector graph. This makes the graph very hard to see when zoomed out.
here is the code:
v_x = np.random.randint(0, 80000, 300000)
v_y = v_x # the x, y cordinate of the dots.
f,axes = plt.subplots(11,11,figsize = (20,20))
for row in range(11):
for col in range(11):
axes[row,col].set_yticklabels([])
axes[row,col].set_xticklabels([])
if row > col:
axes[row,col].axis('off')
else:
axes[row,col].set_xlim(0,len(v_x))
axes[row,col].set_ylim(0,len(v_y))
axes[row,col].scatter(v_x,v_y, c = '#000000', s=(72./300)**2*20, marker = 's', edgecolor= '', rasterized = True)
f.savefig('{}'.format('test.pdf'), facecolor='w', bbox_inches='tight', dpi = 300)
If I don't do the rasteration, the pdf file contains too many dots and cannot be opened, if I do rasteration, the plot is hard to see when zoomed out.
I wonder if there is any way that I can solve this problem.
I would like to draw a plot with a logarithmic y axis and a linear x axis on a square plot area in matplotlib. I can draw linear-linear as well as log-log plots on squares, but the method I use, Axes.set_aspect(...), is not implemented for log-linear plots. Is there a good workaround?
linear-linear plot on a square:
from pylab import *
x = linspace(1,10,1000)
y = sin(x)**2+0.5
plot (x,y)
ax = gca()
data_aspect = ax.get_data_ratio()
ax.set_aspect(1./data_aspect)
show()
log-log plot on a square:
from pylab import *
x = linspace(1,10,1000)
y = sin(x)**2+0.5
plot (x,y)
ax = gca()
ax.set_yscale("log")
ax.set_xscale("log")
xmin,xmax = ax.get_xbound()
ymin,ymax = ax.get_ybound()
data_aspect = (log(ymax)-log(ymin))/(log(xmax)-log(xmin))
ax.set_aspect(1./data_aspect)
show()
But when I try this with a log-linear plot, I do not get the square area, but a warning
from pylab import *
x = linspace(1,10,1000)
y = sin(x)**2+0.5
plot (x,y)
ax = gca()
ax.set_yscale("log")
xmin,xmax = ax.get_xbound()
ymin,ymax = ax.get_ybound()
data_aspect = (log(ymax)-log(ymin))/(xmax-xmin)
ax.set_aspect(1./data_aspect)
show()
yielding the warning:
axes.py:1173: UserWarning: aspect is not supported for Axes with xscale=linear, yscale=log
Is there a good way of achieving square log-linear plots despite the lack support in Axes.set_aspect?
Well, there is a sort of a workaround. The actual axis area (the area where the plot is, not including external ticks &c) can be resized to any size you want it to have.
You may use the ax.set_position to set the relative (to the figure) size and position of the plot. In order to use it in your case we need a bit of maths:
from pylab import *
x = linspace(1,10,1000)
y = sin(x)**2+0.5
plot (x,y)
ax = gca()
ax.set_yscale("log")
# now get the figure size in real coordinates:
fig = gcf()
fwidth = fig.get_figwidth()
fheight = fig.get_figheight()
# get the axis size and position in relative coordinates
# this gives a BBox object
bb = ax.get_position()
# calculate them into real world coordinates
axwidth = fwidth * (bb.x1 - bb.x0)
axheight = fheight * (bb.y1 - bb.y0)
# if the axis is wider than tall, then it has to be narrowe
if axwidth > axheight:
# calculate the narrowing relative to the figure
narrow_by = (axwidth - axheight) / fwidth
# move bounding box edges inwards the same amount to give the correct width
bb.x0 += narrow_by / 2
bb.x1 -= narrow_by / 2
# else if the axis is taller than wide, make it vertically smaller
# works the same as above
elif axheight > axwidth:
shrink_by = (axheight - axwidth) / fheight
bb.y0 += shrink_by / 2
bb.y1 -= shrink_by / 2
ax.set_position(bb)
show()
A slight stylistic comment is that import pylab is not usually used. The lore goes:
import matplotlib.pyplot as plt
pylab as an odd mixture of numpy and matplotlib imports created to make interactive IPython use easier. (I use it, too.)
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!