sidebarDepth: 3

sidebar: auto

origin and extent in imshow

imshow() allows you to render an image (either a 2D array which will be color-mapped (based on norm and cmap) or and 3D RGB(A) array which will be used as-is) to a rectangular region in dataspace. The orientation of the image in the final rendering is controlled by the origin and extent kwargs (and attributes on the resulting AxesImage instance) and the data limits of the axes.

The extent kwarg controls the bounding box in data coordinates that the image will fill specified as (left, right, bottom, top) in data coordinates, the origin kwarg controls how the image fills that bounding box, and the orientation in the final rendered image is also affected by the axes limits.

Most of the code below is used for adding labels and informative text to the plots. The described effects of origin and extent can be seen in the plots without the need to follow all code details.

For a quick understanding, you may want to skip the code details below and directly continue with the discussion of the results.

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib.gridspec import GridSpec
  4. def index_to_coordinate(index, extent, origin):
  5. """Return the pixel center of an index."""
  6. left, right, bottom, top = extent
  7. hshift = 0.5 * np.sign(right - left)
  8. left, right = left + hshift, right - hshift
  9. vshift = 0.5 * np.sign(top - bottom)
  10. bottom, top = bottom + vshift, top - vshift
  11. if origin == 'upper':
  12. bottom, top = top, bottom
  13. return {
  14. "[0, 0]": (left, bottom),
  15. "[M', 0]": (left, top),
  16. "[0, N']": (right, bottom),
  17. "[M', N']": (right, top),
  18. }[index]
  19. def get_index_label_pos(index, extent, origin, inverted_xindex):
  20. """
  21. Return the desired position and horizontal alignment of an index label.
  22. """
  23. if extent is None:
  24. extent = lookup_extent(origin)
  25. left, right, bottom, top = extent
  26. x, y = index_to_coordinate(index, extent, origin)
  27. is_x0 = index[-2:] == "0]"
  28. halign = 'left' if is_x0 ^ inverted_xindex else 'right'
  29. hshift = 0.5 * np.sign(left - right)
  30. x += hshift * (1 if is_x0 else -1)
  31. return x, y, halign
  32. def get_color(index, data, cmap):
  33. """Return the data color of an index."""
  34. val = {
  35. "[0, 0]": data[0, 0],
  36. "[0, N']": data[0, -1],
  37. "[M', 0]": data[-1, 0],
  38. "[M', N']": data[-1, -1],
  39. }[index]
  40. return cmap(val / data.max())
  41. def lookup_extent(origin):
  42. """Return extent for label positioning when not given explicitly."""
  43. if origin == 'lower':
  44. return (-0.5, 6.5, -0.5, 5.5)
  45. else:
  46. return (-0.5, 6.5, 5.5, -0.5)
  47. def set_extent_None_text(ax):
  48. ax.text(3, 2.5, 'equals\nextent=None', size='large',
  49. ha='center', va='center', color='w')
  50. def plot_imshow_with_labels(ax, data, extent, origin, xlim, ylim):
  51. """Actually run ``imshow()`` and add extent and index labels."""
  52. im = ax.imshow(data, origin=origin, extent=extent)
  53. # extent labels (left, right, bottom, top)
  54. left, right, bottom, top = im.get_extent()
  55. if xlim is None or top > bottom:
  56. upper_string, lower_string = 'top', 'bottom'
  57. else:
  58. upper_string, lower_string = 'bottom', 'top'
  59. if ylim is None or left < right:
  60. port_string, starboard_string = 'left', 'right'
  61. inverted_xindex = False
  62. else:
  63. port_string, starboard_string = 'right', 'left'
  64. inverted_xindex = True
  65. bbox_kwargs = {'fc': 'w', 'alpha': .75, 'boxstyle': "round4"}
  66. ann_kwargs = {'xycoords': 'axes fraction',
  67. 'textcoords': 'offset points',
  68. 'bbox': bbox_kwargs}
  69. ax.annotate(upper_string, xy=(.5, 1), xytext=(0, -1),
  70. ha='center', va='top', **ann_kwargs)
  71. ax.annotate(lower_string, xy=(.5, 0), xytext=(0, 1),
  72. ha='center', va='bottom', **ann_kwargs)
  73. ax.annotate(port_string, xy=(0, .5), xytext=(1, 0),
  74. ha='left', va='center', rotation=90,
  75. **ann_kwargs)
  76. ax.annotate(starboard_string, xy=(1, .5), xytext=(-1, 0),
  77. ha='right', va='center', rotation=-90,
  78. **ann_kwargs)
  79. ax.set_title('origin: {origin}'.format(origin=origin))
  80. # index labels
  81. for index in ["[0, 0]", "[0, N']", "[M', 0]", "[M', N']"]:
  82. tx, ty, halign = get_index_label_pos(index, extent, origin,
  83. inverted_xindex)
  84. facecolor = get_color(index, data, im.get_cmap())
  85. ax.text(tx, ty, index, color='white', ha=halign, va='center',
  86. bbox={'boxstyle': 'square', 'facecolor': facecolor})
  87. if xlim:
  88. ax.set_xlim(*xlim)
  89. if ylim:
  90. ax.set_ylim(*ylim)
  91. def generate_imshow_demo_grid(extents, xlim=None, ylim=None):
  92. N = len(extents)
  93. fig = plt.figure(tight_layout=True)
  94. fig.set_size_inches(6, N * (11.25) / 5)
  95. gs = GridSpec(N, 5, figure=fig)
  96. columns = {'label': [fig.add_subplot(gs[j, 0]) for j in range(N)],
  97. 'upper': [fig.add_subplot(gs[j, 1:3]) for j in range(N)],
  98. 'lower': [fig.add_subplot(gs[j, 3:5]) for j in range(N)]}
  99. x, y = np.ogrid[0:6, 0:7]
  100. data = x + y
  101. for origin in ['upper', 'lower']:
  102. for ax, extent in zip(columns[origin], extents):
  103. plot_imshow_with_labels(ax, data, extent, origin, xlim, ylim)
  104. for ax, extent in zip(columns['label'], extents):
  105. text_kwargs = {'ha': 'right',
  106. 'va': 'center',
  107. 'xycoords': 'axes fraction',
  108. 'xy': (1, .5)}
  109. if extent is None:
  110. ax.annotate('None', **text_kwargs)
  111. ax.set_title('extent=')
  112. else:
  113. left, right, bottom, top = extent
  114. text = ('left: {left:0.1f}\nright: {right:0.1f}\n' +
  115. 'bottom: {bottom:0.1f}\ntop: {top:0.1f}\n').format(
  116. left=left, right=right, bottom=bottom, top=top)
  117. ax.annotate(text, **text_kwargs)
  118. ax.axis('off')
  119. return columns

Default extent

First, let’s have a look at the default extent=None

  1. generate_imshow_demo_grid(extents=[None])

sphx_glr_imshow_extent_001

Generally, for an array of shape (M, N), the first index runs along the vertical, the second index runs along the horizontal. The pixel centers are at integer positions ranging from 0 to N' = N - 1 horizontally and from 0 to M' = M - 1 vertically. origin determines how to the data is filled in the bounding box.

For origin='lower':

  • [0, 0] is at (left, bottom)
  • [M’, 0] is at (left, top)
  • [0, N’] is at (right, bottom)
  • [M’, N’] is at (right, top)

origin='upper' reverses the vertical axes direction and filling:

  • [0, 0] is at (left, top)
  • [M’, 0] is at (left, bottom)
  • [0, N’] is at (right, top)
  • [M’, N’] is at (right, bottom)

In summary, the position of the [0, 0] index as well as the extent are influenced by origin:


origin [0, 0] position extent

upper top left (-0.5, numcols-0.5, numrows-0.5, -0.5)

lower bottom left (-0.5, numcols-0.5, -0.5, numrows-0.5)

The default value of origin is set by rcParams["image.origin"] = 'upper' which defaults to 'upper' to match the matrix indexing conventions in math and computer graphics image indexing conventions.

Explicit extent

By setting extent we define the coordinates of the image area. The underlying image data is interpolated/resampled to fill that area.

If the axes is set to autoscale, then the view limits of the axes are set to match the extent which ensures that the coordinate set by (left, bottom) is at the bottom left of the axes! However, this may invert the axis so they do not increase in the ‘natural’ direction.

  1. extents = [(-0.5, 6.5, -0.5, 5.5),
  2. (-0.5, 6.5, 5.5, -0.5),
  3. (6.5, -0.5, -0.5, 5.5),
  4. (6.5, -0.5, 5.5, -0.5)]
  5. columns = generate_imshow_demo_grid(extents)
  6. set_extent_None_text(columns['upper'][1])
  7. set_extent_None_text(columns['lower'][0])

sphx_glr_imshow_extent_002

Explicit extent and axes limits

If we fix the axes limits by explicitly setting set_xlim / set_ylim, we force a certain size and orientation of the axes. This can decouple the ‘left-right’ and ‘top-bottom’ sense of the image from the orientation on the screen.

In the example below we have chosen the limits slightly larger than the extent (note the white areas within the Axes).

While we keep the extents as in the examples before, the coordinate (0, 0) is now explicitly put at the bottom left and values increase to up and to the right (from the viewer point of view). We can see that:

  • The coordinate (left, bottom) anchors the image which then fills the box going towards the (right, top) point in data space.
  • The first column is always closest to the ‘left’.
  • origin controls if the first row is closest to ‘top’ or ‘bottom’.
  • The image may be inverted along either direction.
  • The ‘left-right’ and ‘top-bottom’ sense of the image may be uncoupled from the orientation on the screen.
  1. generate_imshow_demo_grid(extents=[None] + extents,
  2. xlim=(-2, 8), ylim=(-1, 6))

sphx_glr_imshow_extent_003

Total running time of the script: ( 0 minutes 2.056 seconds)

Download