Related
I am trying to understand this code snippet:
def add_inset(ax, rect, *args, **kwargs):
box = ax.get_position()
inax_position = ax.transAxes.transform(rect[0:2])
infig_position = ax.figure.transFigure.inverted().transform(inax_position)
new_rect = list(infig_position) + [box.width * rect[2], box.height * rect[3]]
return fig.add_axes(new_rect, *args, **kwargs)
This code adds an inset to an existing figure. It looks like this:
The original code is from this notebook file.
I don't understand why two coordinates transformation are needed:
inax_position = ax.transAxes.transform(rect[0:2])
infig_position = ax.figure.transFigure.inverted().transform(inax_position)
Explanation
In the method add_inset(ax, rect), rect is a rectangle in axes coordinates. That makes sense because you often want to specify the location of the inset relavtive to the axes in which it lives.
However in order to later be able to create a new axes, the axes position needs to be known in figure coordinates, which can then be given to fig.add_axes(figurecoordinates).
So what is needed is a coordinate transform from axes coordinates to figure coordinates. This is performed here in a two-step process:
Transform from axes coords to display coords using transAxes.
Transform from display coords to figure coords using the inverse of transFigure.
This two step procedure could be further condensed in a single transform like
mytrans = ax.transAxes + ax.figure.transFigure.inverted()
infig_position = mytrans.transform(rect[0:2])
It may be of interest to read the matplotlib transformation tutorial on how transformations work.
Alternatives
The above might not be the most obvious method to place an inset. Matplotlib provides some tools itself. A convenient method is the mpl_toolkits.axes_grid1.inset_locator. Below are two ways to use its inset_axes method when creating insets in axes coordinates.
import matplotlib.pyplot as plt
import mpl_toolkits.axes_grid1.inset_locator as il
fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(4,4))
ax1.plot([1,2,3],[2.2,2,3])
# set the inset at upper left (loc=2) with width, height=0.5,0.4
axins = il.inset_axes(ax1, "50%", "40%", loc=2, borderpad=1)
axins.scatter([1,2,3],[3,2,3])
# set the inset at 0.2,0.5, with width, height=0.8,0.4
# in parent axes coordinates
axins2 = il.inset_axes(ax2, "100%", "100%", loc=3, borderpad=0,
bbox_to_anchor=(0.2,0.5,0.7,0.4),bbox_transform=ax2.transAxes,)
axins2.scatter([1,2,3],[3,2,3])
plt.show()
I'm working on some matplotlib plots and need to have a zoomed inset. This is possible with the zoomed_inset_axes from the axes_grid1 toolkit. See the example here:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
import numpy as np
def get_demo_image():
from matplotlib.cbook import get_sample_data
import numpy as np
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
z = np.load(f)
# z is a numpy array of 15x15
return z, (-3,4,-4,3)
fig, ax = plt.subplots(figsize=[5,4])
# prepare the demo image
Z, extent = get_demo_image()
Z2 = np.zeros([150, 150], dtype="d")
ny, nx = Z.shape
Z2[30:30+ny, 30:30+nx] = Z
# extent = [-3, 4, -4, 3]
ax.imshow(Z2, extent=extent, interpolation="nearest",
origin="lower")
axins = zoomed_inset_axes(ax, 6, loc=1) # zoom = 6
axins.imshow(Z2, extent=extent, interpolation="nearest",
origin="lower")
# sub region of the original image
x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
plt.xticks(visible=False)
plt.yticks(visible=False)
# draw a bbox of the region of the inset axes in the parent axes and
# connecting lines between the bbox and the inset axes area
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
plt.draw()
plt.show()
This will give the desired result:
http://matplotlib.org/1.3.1/_images/inset_locator_demo21.png
But as you can see in the code, the data has to be plotted twice - once for the main axis (ax.imshow...) and once for the inset axis (axins.imshow...).
My question is:
Is there a way to add a zoomed inset after the main plot is completed, without the need to plot everything again on the new axis?
Please note: I am not looking for a solution which wraps the plot call with a function and let the function plot ax and axins (see example below), but (if this exists) a native solution that makes use of the existing data in ax. Anybody knows if such a solution exists?
This is the wrapper-solution:
def plot_with_zoom(*args, **kwargs):
ax.imshow(*args, **kwargs)
axins.imshow(*args, **kwargs)
It works, but it feels a bit like a hack, since why should I need to plot all data again if I just want to zoom into a region of my existing plot.
Some additional clarification after the answer by ed-smith:
The example above is of course only the minimal example. There could be many different sets of data in the plot (and with sets of data I mean things plotted via imshow or plot etc). Imagine for example a scatter plot with 10 arrays of points, all plotted vs. common x.
As I wrote above, the most direct way to do that is just have a wrapper to plot the data in all instances. But what I'm looking for is a way (if it exists) to start with the final ax object (not the individual plotting commands) and somehow create the zoomed inset.
I think the following does what you want. Note that you use the returned handle to the first imshow and add it to the axis for the insert. You need to make a copy so you have a separate handle for each figure,
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
import numpy as np
import copy
def get_demo_image():
from matplotlib.cbook import get_sample_data
import numpy as np
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
z = np.load(f)
# z is a numpy array of 15x15
return z, (-3,4,-4,3)
fig, ax = plt.subplots(figsize=[5,4])
# prepare the demo image
Z, extent = get_demo_image()
Z2 = np.zeros([150, 150], dtype="d")
ny, nx = Z.shape
Z2[30:30+ny, 30:30+nx] = Z
# extent = [-3, 4, -4, 3]
im = ax.imshow(Z2, extent=extent, interpolation="nearest",
origin="lower")
#Without copy, image is shown in insert only
imcopy = copy.copy(im)
axins = zoomed_inset_axes(ax, 6, loc=1) # zoom = 6
axins.add_artist(imcopy)
# sub region of the original image
x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
plt.xticks(visible=False)
plt.yticks(visible=False)
# draw a bbox of the region of the inset axes in the parent axes and
# connecting lines between the bbox and the inset axes area
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
plt.draw()
plt.show()
For your wrapper function, this would be something like,
def plot_with_zoom(*args, **kwargs):
im = ax.imshow(*args, **kwargs)
imcopy = copy.copy(im)
axins.add_artist(imcopy)
However, as imshow just displays the data stored in array Z as an image, I would think this solution would actually be slower than two separate calls to imshow. For plots which take more time, e.g. a contour plot or pcolormesh, this approach may be sensible...
EDIT:
Beyond a single imshow, and for multiple plots of different types. Plotting functions all return different handles (e.g. plot returns a list of lines, imshow returns a matplotlib.image.AxesImage, etc). You could keep adding these handles to a list (or dict) as you plot (or use a collection if they are similar enough). Then you could write a general function which adds them to an axis using add_artist or add_patch methods from the zoomed axis, probably with if type checking to deal with the various types used in the plot. A simpler method may be to loop over ax.get_children() and reuse anything which isn't an element of the axis itself.
Another option may be to look into blitting techniques, rasterization or other techniques used to speed up animation, for example using fig.canvas.copy_from_bbox or fig.canvas.tostring_rgb to copy the entire figure as an image (see why is plotting with Matplotlib so slow?low). You could also draw the figure, save it to a non-vector graphic (with savefig or to a StringIO buffer), read back in and plot a zoomed in version.
Update: The solution below doesn't work in newer versions of matplotlib because some of the internal APIs have changed. For newer versions of matplotlib you can use https://github.com/matplotlib/matplotview, which provides the same functionality as this answer and some additional functionality.
I recently worked on a solution to this problem in a piece of software I am writing, and decided to share it here in case anyone is still dealing with this issue. This solution requires no replotting, simply the use of a custom zoom axes class instead of the default one. It works using a custom Renderer, which acts as a middle-man between the matplotlib Artists and the actual Renderer. Artists are then simply drawn using the custom Renderer instead of the original Renderer provided. Below is the implementation:
from matplotlib.path import Path
from matplotlib.axes import Axes
from matplotlib.axes._axes import _make_inset_locator
from matplotlib.transforms import Bbox, Transform, IdentityTransform, Affine2D
from matplotlib.backend_bases import RendererBase
import matplotlib._image as _image
import numpy as np
class TransformRenderer(RendererBase):
"""
A matplotlib renderer which performs transforms to change the final location of plotted
elements, and then defers drawing work to the original renderer.
"""
def __init__(self, base_renderer: RendererBase, mock_transform: Transform, transform: Transform,
bounding_axes: Axes):
"""
Constructs a new TransformRender.
:param base_renderer: The renderer to use for finally drawing objects.
:param mock_transform: The transform or coordinate space which all passed paths/triangles/images will be
converted to before being placed back into display coordinates by the main transform.
For example if the parent axes transData is passed, all objects will be converted to
the parent axes data coordinate space before being transformed via the main transform
back into coordinate space.
:param transform: The main transform to be used for plotting all objects once converted into the mock_transform
coordinate space. Typically this is the child axes data coordinate space (transData).
:param bounding_axes: The axes to plot everything within. Everything outside of this axes will be clipped.
"""
super().__init__()
self.__renderer = base_renderer
self.__mock_trans = mock_transform
self.__core_trans = transform
self.__bounding_axes = bounding_axes
def _get_axes_display_box(self) -> Bbox:
"""
Private method, get the bounding box of the child axes in display coordinates.
"""
return self.__bounding_axes.patch.get_bbox().transformed(self.__bounding_axes.transAxes)
def _get_transfer_transform(self, orig_transform):
"""
Private method, returns the transform which translates and scales coordinates as if they were originally
plotted on the child axes instead of the parent axes.
:param orig_transform: The transform that was going to be originally used by the object/path/text/image.
:return: A matplotlib transform which goes from original point data -> display coordinates if the data was
originally plotted on the child axes instead of the parent axes.
"""
# We apply the original transform to go to display coordinates, then apply the parent data transform inverted
# to go to the parent axes coordinate space (data space), then apply the child axes data transform to
# go back into display space, but as if we originally plotted the artist on the child axes....
return orig_transform + self.__mock_trans.inverted() + self.__core_trans
# We copy all of the properties of the renderer we are mocking, so that artists plot themselves as if they were
# placed on the original renderer.
#property
def height(self):
return self.__renderer.get_canvas_width_height()[1]
#property
def width(self):
return self.__renderer.get_canvas_width_height()[0]
def get_text_width_height_descent(self, s, prop, ismath):
return self.__renderer.get_text_width_height_descent(s, prop, ismath)
def get_canvas_width_height(self):
return self.__renderer.get_canvas_width_height()
def get_texmanager(self):
return self.__renderer.get_texmanager()
def get_image_magnification(self):
return self.__renderer.get_image_magnification()
def _get_text_path_transform(self, x, y, s, prop, angle, ismath):
return self.__renderer._get_text_path_transform(x, y, s, prop, angle, ismath)
def option_scale_image(self):
return False
def points_to_pixels(self, points):
return self.__renderer.points_to_pixels(points)
def flipy(self):
return self.__renderer.flipy()
# Actual drawing methods below:
def draw_path(self, gc, path: Path, transform: Transform, rgbFace=None):
# Convert the path to display coordinates, but if it was originally drawn on the child axes.
path = path.deepcopy()
path.vertices = self._get_transfer_transform(transform).transform(path.vertices)
bbox = self._get_axes_display_box()
# We check if the path intersects the axes box at all, if not don't waste time drawing it.
if(not path.intersects_bbox(bbox, True)):
return
# Change the clip to the sub-axes box
gc.set_clip_rectangle(bbox)
self.__renderer.draw_path(gc, path, IdentityTransform(), rgbFace)
def _draw_text_as_path(self, gc, x, y, s: str, prop, angle, ismath):
# If the text field is empty, don't even try rendering it...
if((s is None) or (s.strip() == "")):
return
# Call the super class instance, which works for all cases except one checked above... (Above case causes error)
super()._draw_text_as_path(gc, x, y, s, prop, angle, ismath)
def draw_gouraud_triangle(self, gc, points, colors, transform):
# Pretty much identical to draw_path, transform the points and adjust clip to the child axes bounding box.
points = self._get_transfer_transform(transform).transform(points)
path = Path(points, closed=True)
bbox = self._get_axes_display_box()
if(not path.intersects_bbox(bbox, True)):
return
gc.set_clip_rectangle(bbox)
self.__renderer.draw_gouraud_triangle(gc, path.vertices, colors, IdentityTransform())
# Images prove to be especially messy to deal with...
def draw_image(self, gc, x, y, im, transform=None):
mag = self.get_image_magnification()
shift_data_transform = self._get_transfer_transform(IdentityTransform())
axes_bbox = self._get_axes_display_box()
# Compute the image bounding box in display coordinates.... Image arrives pre-magnified.
img_bbox_disp = Bbox.from_bounds(x, y, im.shape[1], im.shape[0])
# Now compute the output location, clipping it with the final axes patch.
out_box = img_bbox_disp.transformed(shift_data_transform)
clipped_out_box = Bbox.intersection(out_box, axes_bbox)
if(clipped_out_box is None):
return
# We compute what the dimensions of the final output image within the sub-axes are going to be.
x, y, out_w, out_h = clipped_out_box.bounds
out_w, out_h = int(np.ceil(out_w * mag)), int(np.ceil(out_h * mag))
if((out_w <= 0) or (out_h <= 0)):
return
# We can now construct the transform which converts between the original image (a 2D numpy array which starts
# at the origin) to the final zoomed image (also a 2D numpy array which starts at the origin).
img_trans = (
Affine2D().scale(1/mag, 1/mag).translate(img_bbox_disp.x0, img_bbox_disp.y0)
+ shift_data_transform
+ Affine2D().translate(-clipped_out_box.x0, -clipped_out_box.y0).scale(mag, mag)
)
# We resize and zoom the original image onto the out_arr.
out_arr = np.zeros((out_h, out_w, im.shape[2]), dtype=im.dtype)
_image.resample(im, out_arr, img_trans, _image.NEAREST, alpha=1)
_image.resample(im[:, :, 3], out_arr[:, :, 3], img_trans, _image.NEAREST, alpha=1)
gc.set_clip_rectangle(clipped_out_box)
x, y = clipped_out_box.x0, clipped_out_box.y0
if(self.option_scale_image()):
self.__renderer.draw_image(gc, x, y, out_arr, None)
else:
self.__renderer.draw_image(gc, x, y, out_arr)
class ZoomViewAxes(Axes):
"""
A zoom axes which automatically displays all of the elements it is currently zoomed in on. Does not require
Artists to be plotted twice.
"""
def __init__(self, axes_of_zoom: Axes, rect: Bbox, transform = None, zorder = 5, **kwargs):
"""
Construct a new zoom axes.
:param axes_of_zoom: The axes to zoom in on which this axes will be nested inside.
:param rect: The bounding box to place this axes in, within the parent axes.
:param transform: The transform to use when placing this axes in the parent axes. Defaults to
'axes_of_zoom.transData'.
:param zorder: An integer, the z-order of the axes. Defaults to 5, which means it is drawn on top of most
object in the plot.
:param kwargs: Any other keyword arguments which the Axes class accepts.
"""
if(transform is None):
transform = axes_of_zoom.transData
inset_loc = _make_inset_locator(rect.bounds, transform, axes_of_zoom)
bb = inset_loc(None, None)
super().__init__(axes_of_zoom.figure, bb.bounds, zorder=zorder, **kwargs)
self.__zoom_axes = axes_of_zoom
self.set_axes_locator(inset_loc)
axes_of_zoom.add_child_axes(self)
def draw(self, renderer=None, inframe=False):
super().draw(renderer, inframe)
if(not self.get_visible()):
return
axes_children = [
*self.__zoom_axes.collections,
*self.__zoom_axes.patches,
*self.__zoom_axes.lines,
*self.__zoom_axes.texts,
*self.__zoom_axes.artists,
*self.__zoom_axes.images
]
img_boxes = []
# We need to temporarily disable the clip boxes of all of the images, in order to allow us to continue
# rendering them it even if it is outside of the parent axes (they might still be visible in this zoom axes).
for img in self.__zoom_axes.images:
img_boxes.append(img.get_clip_box())
img.set_clip_box(img.get_window_extent(renderer))
# Sort all rendered item by their z-order so the render in layers correctly...
axes_children.sort(key=lambda obj: obj.get_zorder())
# Construct mock renderer and draw all artists to it.
mock_renderer = TransformRenderer(renderer, self.__zoom_axes.transData, self.transData, self)
for artist in axes_children:
if(artist is not self):
artist.draw(mock_renderer)
# Reset all of the image clip boxes...
for img, box in zip(self.__zoom_axes.images, img_boxes):
img.set_clip_box(box)
# We need to redraw the splines if enabled, as we have finally drawn everything... This avoids other objects
# being drawn over the splines
if(self.axison and self._frameon):
for spine in self.spines.values():
spine.draw(renderer)
The example done using the custom zoom axes:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
from zoomaxes import ZoomViewAxes
from matplotlib.transforms import Bbox
import numpy as np
def get_demo_image():
from matplotlib.cbook import get_sample_data
import numpy as np
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
z = np.load(f)
# z is a numpy array of 15x15
return z, (-3, 4, -4, 3)
fig, ax = plt.subplots(figsize=[5, 4])
# prepare the demo image
Z, extent = get_demo_image()
Z2 = np.zeros([150, 150], dtype="d")
ny, nx = Z.shape
Z2[30:30 + ny, 30:30 + nx] = Z
# extent = [-3, 4, -4, 3]
ax.imshow(Z2, extent=extent, interpolation="nearest",
origin="lower")
axins = ZoomViewAxes(ax, Bbox.from_bounds(0.6, 0.6, 0.35, 0.35), ax.transAxes) # Use the new zoom axes...
# sub region of the original image
x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
plt.xticks(visible=False)
plt.yticks(visible=False)
# draw a bbox of the region of the inset axes in the parent axes and
# connecting lines between the bbox and the inset axes area
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
plt.draw()
plt.show()
Result
Nearly identical image of plot shown in question:
Advantages:
Fully automatic, and will redraw when changes are made to the plot.
Works on pretty much all artists. (I have personally tested lines, boxes, arrows, text, and images)
Avoids using blitting techniques, meaning zoom quality/depth is infinitely high. (Exception would be zooming on images obviously)
Disadvantages:
Not as fast as bliting techniques. All artists of the parent axes have to be looped over and drawn for every ZoomViewAxes instance.
My question is a bit similar to this question that draws line with width given in data coordinates. What makes my question a bit more challenging is that unlike the linked question, the segment that I wish to expand is of a random orientation.
Let's say if the line segment goes from (0, 10) to (10, 10), and I wish to expand it to a width of 6. Then it is simply
x = [0, 10]
y = [10, 10]
ax.fill_between(x, y - 3, y + 3)
However, my line segment is of random orientation. That is, it is not necessarily along x-axis or y-axis. It has a certain slope.
A line segment s is defined as a list of its starting and ending points: [(x1, y1), (x2, y2)].
Now I wish to expand the line segment to a certain width w. The solution is expected to work for a line segment in any orientation. How to do this?
plt.plot(x, y, linewidth=6.0) cannot do the trick, because I want my width to be in the same unit as my data.
The following code is a generic example on how to make a line plot in matplotlib using data coordinates as linewidth. There are two solutions; one using callbacks, one using subclassing Line2D.
Using callbacks.
It is implemted as a class data_linewidth_plot that can be called with a signature pretty close the the normal plt.plot command,
l = data_linewidth_plot(x, y, ax=ax, label='some line', linewidth=1, alpha=0.4)
where ax is the axes to plot to. The ax argument can be omitted, when only one subplot exists in the figure. The linewidth argument is interpreted in (y-)data units.
Further features:
It's independend on the subplot placements, margins or figure size.
If the aspect ratio is unequal, it uses y data coordinates as the linewidth.
It also takes care that the legend handle is correctly set (we may want to have a huge line in the plot, but certainly not in the legend).
It is compatible with changes to the figure size, zoom or pan events, as it takes care of resizing the linewidth on such events.
Here is the complete code.
import matplotlib.pyplot as plt
class data_linewidth_plot():
def __init__(self, x, y, **kwargs):
self.ax = kwargs.pop("ax", plt.gca())
self.fig = self.ax.get_figure()
self.lw_data = kwargs.pop("linewidth", 1)
self.lw = 1
self.fig.canvas.draw()
self.ppd = 72./self.fig.dpi
self.trans = self.ax.transData.transform
self.linehandle, = self.ax.plot([],[],**kwargs)
if "label" in kwargs: kwargs.pop("label")
self.line, = self.ax.plot(x, y, **kwargs)
self.line.set_color(self.linehandle.get_color())
self._resize()
self.cid = self.fig.canvas.mpl_connect('draw_event', self._resize)
def _resize(self, event=None):
lw = ((self.trans((1, self.lw_data))-self.trans((0, 0)))*self.ppd)[1]
if lw != self.lw:
self.line.set_linewidth(lw)
self.lw = lw
self._redraw_later()
def _redraw_later(self):
self.timer = self.fig.canvas.new_timer(interval=10)
self.timer.single_shot = True
self.timer.add_callback(lambda : self.fig.canvas.draw_idle())
self.timer.start()
fig1, ax1 = plt.subplots()
#ax.set_aspect('equal') #<-not necessary
ax1.set_ylim(0,3)
x = [0,1,2,3]
y = [1,1,2,2]
# plot a line, with 'linewidth' in (y-)data coordinates.
l = data_linewidth_plot(x, y, ax=ax1, label='some 1 data unit wide line',
linewidth=1, alpha=0.4)
plt.legend() # <- legend possible
plt.show()
(I updated the code to use a timer to redraw the canvas, due to this issue)
Subclassing Line2D
The above solution has some drawbacks. It requires a timer and callbacks to update itself on changing axis limits or figure size. The following is a solution without such needs. It will use a dynamic property to always calculate the linewidth in points from the desired linewidth in data coordinates on the fly. It is much shorter than the above.
A drawback here is that a legend needs to be created manually via a proxyartist.
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
class LineDataUnits(Line2D):
def __init__(self, *args, **kwargs):
_lw_data = kwargs.pop("linewidth", 1)
super().__init__(*args, **kwargs)
self._lw_data = _lw_data
def _get_lw(self):
if self.axes is not None:
ppd = 72./self.axes.figure.dpi
trans = self.axes.transData.transform
return ((trans((1, self._lw_data))-trans((0, 0)))*ppd)[1]
else:
return 1
def _set_lw(self, lw):
self._lw_data = lw
_linewidth = property(_get_lw, _set_lw)
fig, ax = plt.subplots()
#ax.set_aspect('equal') # <-not necessary, if not given, y data is assumed
ax.set_xlim(0,3)
ax.set_ylim(0,3)
x = [0,1,2,3]
y = [1,1,2,2]
line = LineDataUnits(x, y, linewidth=1, alpha=0.4)
ax.add_line(line)
ax.legend([Line2D([],[], linewidth=3, alpha=0.4)],
['some 1 data unit wide line']) # <- legend possible via proxy artist
plt.show()
Just to add to the previous answer (can't comment yet), here's a function that automates this process without the need for equal axes or the heuristic value of 0.8 for labels. The data limits and size of the axis need to be fixed and not changed after this function is called.
def linewidth_from_data_units(linewidth, axis, reference='y'):
"""
Convert a linewidth in data units to linewidth in points.
Parameters
----------
linewidth: float
Linewidth in data units of the respective reference-axis
axis: matplotlib axis
The axis which is used to extract the relevant transformation
data (data limits and size must not change afterwards)
reference: string
The axis that is taken as a reference for the data width.
Possible values: 'x' and 'y'. Defaults to 'y'.
Returns
-------
linewidth: float
Linewidth in points
"""
fig = axis.get_figure()
if reference == 'x':
length = fig.bbox_inches.width * axis.get_position().width
value_range = np.diff(axis.get_xlim())
elif reference == 'y':
length = fig.bbox_inches.height * axis.get_position().height
value_range = np.diff(axis.get_ylim())
# Convert length to points
length *= 72
# Scale linewidth to value range
return linewidth * (length / value_range)
Explanation:
Set up the figure with a known height and make the scale of the two axes equal (or else the idea of "data coordinates" does not apply). Make sure the proportions of the figure match the expected proportions of the x and y axes.
Compute the height of the whole figure point_hei (including margins) in units of points by multiplying inches by 72
Manually assign the y-axis range yrange (You could do this by plotting a "dummy" series first and then querying the plot axis to get the lower and upper y limits.)
Provide the width of the line that you would like in data units linewid
Calculate what those units would be in points pointlinewid while adjusting for the margins. In a single-frame plot, the plot is 80% of the full image height.
Plot the lines, using a capstyle that does not pad the ends of the line (has a big effect at these large line sizes)
Voilà? (Note: this should generate the proper image in the saved file, but no guarantees if you resize a plot window.)
import matplotlib.pyplot as plt
rez=600
wid=8.0 # Must be proportional to x and y limits below
hei=6.0
fig = plt.figure(1, figsize=(wid, hei))
sp = fig.add_subplot(111)
# # plt.figure.tight_layout()
# fig.set_autoscaley_on(False)
sp.set_xlim([0,4000])
sp.set_ylim([0,3000])
plt.axes().set_aspect('equal')
# line is in points: 72 points per inch
point_hei=hei*72
xval=[100,1300,2200,3000,3900]
yval=[10,200,2500,1750,1750]
x1,x2,y1,y2 = plt.axis()
yrange = y2 - y1
# print yrange
linewid = 500 # in data units
# For the calculation below, you have to adjust width by 0.8
# because the top and bottom 10% of the figure are labels & axis
pointlinewid = (linewid * (point_hei/yrange)) * 0.8 # corresponding width in pts
plt.plot(xval,yval,linewidth = pointlinewid,color="blue",solid_capstyle="butt")
# just for fun, plot the half-width line on top of it
plt.plot(xval,yval,linewidth = pointlinewid/2,color="red",solid_capstyle="butt")
plt.savefig('mymatplot2.png',dpi=rez)
I am trying to create a 3D bar histogram in Python using bar3d() in Matplotlib.
I have got to the point where I can display my histogram on the screen after passing it some data, but I am stuck on the following:
Displaying axes labels correctly (currently misses out final (or initial?) tick labels)
Either making the ticks on each axis (e.g. that for 'Mon') either point to it's corresponding blue bar, or position the tick label for between the major tick marks.
Making the bars semi-transparent.
image of plot uploaded here
I have tried passing several different arguments to the 'ax' instance, but have not got anything to work despite and suspect I have misunderstood what to provide it with. I will be very grateful for any help on this at all.
Here is a sample of the code i'm working on:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
#from IPython.Shell import IPShellEmbed
#sh = IPShellEmbed()
data = np.array([
[0,1,0,2,0],
[0,3,0,2,0],
[6,1,1,7,0],
[0,5,0,2,9],
[0,1,0,4,0],
[9,1,3,4,2],
[0,0,2,1,3],
])
column_names = ['a','b','c','d','e']
row_names = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
fig = plt.figure()
ax = Axes3D(fig)
lx= len(data[0]) # Work out matrix dimensions
ly= len(data[:,0])
xpos = np.arange(0,lx,1) # Set up a mesh of positions
ypos = np.arange(0,ly,1)
xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25)
xpos = xpos.flatten() # Convert positions to 1D array
ypos = ypos.flatten()
zpos = np.zeros(lx*ly)
dx = 0.5 * np.ones_like(zpos)
dy = dx.copy()
dz = data.flatten()
ax.bar3d(xpos,ypos,zpos, dx, dy, dz, color='b')
#sh()
ax.w_xaxis.set_ticklabels(column_names)
ax.w_yaxis.set_ticklabels(row_names)
ax.set_xlabel('Letter')
ax.set_ylabel('Day')
ax.set_zlabel('Occurrence')
plt.show()
To make the bars semi-transparent, you just have to use the alpha parameter. alpha=0 means 100% transparent, while alpha=1 (the default) means 0% transparent.
Try this, it will work out to make the bars semi-transparent:
ax.bar3d(xpos,ypos,zpos, dx, dy, dz, color='b', alpha=0.5)
Regarding the ticks location, you can do it using something like this (the first list on plt.xticks or plt.yticks contains the "values" where do you want to locate the ticks, and the second list contains what you actually want to call the ticks):
#ax.w_xaxis.set_ticklabels(column_names)
#ax.w_yaxis.set_ticklabels(row_names)
ticksx = np.arange(0.5, 5, 1)
plt.xticks(ticksx, column_names)
ticksy = np.arange(0.6, 7, 1)
plt.yticks(ticksy, row_names)
In the end, I get this figure:
I have a very simple basic bar's graphic like this one
but i want to display the bars with some 3d effect, like this
I just want the bars to have that 3d effect...my code is:
fig = Figure(figsize=(4.6,4))
ax1 = fig.add_subplot(111,ylabel="Valeur",xlabel="Code",autoscale_on=True)
width = 0.35
ind = np.arange(len(values))
rects = ax1.bar(ind, values, width, color='#A1B214')
ax1.set_xticks(ind+width)
ax1.set_xticklabels( codes )
ax1.set_ybound(-1,values[0] * 1.1)
canvas = FigureCanvas(fig)
response = HttpResponse(content_type='image/png')
canvas.print_png(response)
i've been looking in the gallery of matplotlib,tried a few things but i wasn't lucky, Any ideas? Thxs
I certainly understand your reason for needing a 3d bar plot; i suspect that's why they were created.
The libraries ('toolkits') in Matplotlib required to create 3D plots are not third-party libraries, etc., rather they are included in the base Matplotlib installation.
(This is true for the current stable version, which is 1.0, though i don't believe it was for 0.98, so the change--from 'add-on' to part of the base install--occurred within the past year, i believe)
So here you are:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as PLT
import numpy as NP
fig = PLT.figure()
ax1 = fig.add_subplot(111, projection='3d')
xpos = NP.random.randint(1, 10, 10)
ypos = NP.random.randint(1, 10, 10)
num_elements = 10
zpos = NP.zeros(num_elements)
dx = NP.ones(10)
dy = NP.ones(10)
dz = NP.random.randint(1, 5, 10)
ax1.bar3d(xpos, ypos, zpos, dx, dy, dz, color='#8E4585')
PLT.show()
To create 3d bars in Maplotlib, you just need to do three (additional) things:
import Axes3D from mpl_toolkits.mplot3d
call the bar3d method (in my scriptlet, it's called by ax1 an instance of the Axes class). The method signature:
bar3d(x, y, z, dy, dz, color='b', zsort="average", *args, **kwargs)
pass in an additional argument to add_subplot, projection='3d'
As far as I know Matplotlib doesn't by design support features like the "3D" effect you just mentioned. I remember reading about this some time back. I don't know it has changed in the meantime.
See this discussion thread for more details.
Update
Take a look at John Porter's mplot3d module. This is not a part of standard matplotlib but a custom extension. Never used it myself so can't say much about its usefulness.