Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

issue with transparency in imshow #16730

Copy link
Copy link
Closed
@pink2289

Description

@pink2289
Issue body actions

Bug report

Hi, I am trying to understand the following example on how to provide an array-like alpha in imshow.

https://matplotlib.org/3.2.0/gallery/images_contours_and_fields/image_transparency_blend.html

However, the exact same script gives me following errors. What is the source of this bug?

Bug summary

ValueError: operands could not be broadcast together with shapes (218,218) (100,100)

Code for reproduction


def normal_pdf(x, mean, var):
    return np.exp(-(x - mean)**2 / (2*var))

# Generate the space in which the blobs will live
xmin, xmax, ymin, ymax = (0, 100, 0, 100)
n_bins = 100
xx = np.linspace(xmin, xmax, n_bins)
yy = np.linspace(ymin, ymax, n_bins)

# Generate the blobs. The range of the values is roughly -.0002 to .0002
means_high = [20, 50]
means_low = [50, 60]
var = [150, 200]

gauss_x_high = normal_pdf(xx, means_high[0], var[0])
gauss_y_high = normal_pdf(yy, means_high[1], var[0])

gauss_x_low = normal_pdf(xx, means_low[0], var[1])
gauss_y_low = normal_pdf(yy, means_low[1], var[1])

weights = (np.outer(gauss_y_high, gauss_x_high) - np.outer(gauss_y_low, gauss_x_low))

# We'll also create a grey background into which the pixels will fade
#greys = np.full((*weights.shape, 3), 70, dtype=np.uint8)

# First we'll plot these blobs using ``imshow`` without transparency.
vmax = np.abs(weights).max()
imshow_kwargs = {
    'vmax': vmax,
    'vmin': -vmax,
    'cmap': 'RdYlBu',
    'extent': (xmin, xmax, ymin, ymax),
}

fig, ax = plt.subplots()
#ax.imshow(greys)
ax.imshow(weights, **imshow_kwargs)
ax.set_axis_off()

# Create an alpha channel of linearly increasing values moving to the right.
alphas = np.ones(weights.shape)
alphas[:, 30:] = np.linspace(1, 0, 70)

# Create the figure and image
# Note that the absolute values may be slightly different
fig, ax = plt.subplots()
#ax.imshow(greys)
ax.imshow(weights, alpha=alphas, **imshow_kwargs)
ax.set_axis_off()

Actual outcome

# If applicable, paste the console output here
#
#
Error in callback <function post_execute at 0x7f4972d48578> (for post_execute):
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/pyplot.pyc in post_execute()
    147             def post_execute():
    148                 if matplotlib.is_interactive():
--> 149                     draw_all()
    150 
    151             # IPython >= 2

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/_pylab_helpers.pyc in draw_all(cls, force)
    134         for f_mgr in cls.get_all_fig_managers():
    135             if force or f_mgr.canvas.figure.stale:
--> 136                 f_mgr.canvas.draw_idle()
    137 
    138 atexit.register(Gcf.destroy_all)

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/backend_bases.pyc in draw_idle(self, *args, **kwargs)
   2053         if not self._is_idle_drawing:
   2054             with self._idle_draw_cntx():
-> 2055                 self.draw(*args, **kwargs)
   2056 
   2057     def draw_cursor(self, event):

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in draw(self)
    435             # if toolbar:
    436             #     toolbar.set_cursor(cursors.WAIT)
--> 437             self.figure.draw(self.renderer)
    438             # A GUI class may be need to update a window using this draw, so
    439             # don't forget to call the superclass.

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/figure.pyc in draw(self, renderer)
   1491 
   1492             mimage._draw_list_compositing_images(
-> 1493                 renderer, self, artists, self.suppressComposite)
   1494 
   1495             renderer.close_group('figure')

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/image.pyc in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    139     if not_composite or not has_images:
    140         for a in artists:
--> 141             a.draw(renderer)
    142     else:
    143         # Composite any adjacent images together

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/axes/_base.pyc in draw(self, renderer, inframe)
   2633             renderer.stop_rasterizing()
   2634 
-> 2635         mimage._draw_list_compositing_images(renderer, self, artists)
   2636 
   2637         renderer.close_group('axes')

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/image.pyc in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    139     if not_composite or not has_images:
    140         for a in artists:
--> 141             a.draw(renderer)
    142     else:
    143         # Composite any adjacent images together

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/image.pyc in draw(self, renderer, *args, **kwargs)
    592         else:
    593             im, l, b, trans = self.make_image(
--> 594                 renderer, renderer.get_image_magnification())
    595             if im is not None:
    596                 renderer.draw_image(gc, l, b, im)

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/image.pyc in make_image(self, renderer, magnification, unsampled)
    840         return self._make_image(
    841             self._A, bbox, transformed_bbox, self.axes.bbox, magnification,
--> 842             unsampled=unsampled)
    843 
    844     def _check_unsampled_image(self, renderer):

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/image.pyc in _make_image(self, A, in_bbox, out_bbox, clip_bbox, magnification, unsampled, round_to_pixel_border)
    520                 alpha_channel = output[:, :, 3]
    521                 alpha_channel[:] = np.asarray(
--> 522                     np.asarray(alpha_channel, np.float32) * out_alpha * alpha,
    523                     np.uint8)
    524 

ValueError: operands could not be broadcast together with shapes (218,218) (100,100) 

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/xxx/anaconda2/lib/python2.7/site-packages/IPython/core/formatters.pyc in __call__(self, obj)
    332                 pass
    333             else:
--> 334                 return printer(obj)
    335             # Finally look for special method names
    336             method = get_real_method(obj, self.print_method)

/xxx/anaconda2/lib/python2.7/site-packages/IPython/core/pylabtools.pyc in <lambda>(fig)
    245 
    246     if 'png' in formats:
--> 247         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
    248     if 'retina' in formats or 'png2x' in formats:
    249         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

/xxx/anaconda2/lib/python2.7/site-packages/IPython/core/pylabtools.pyc in print_figure(fig, fmt, bbox_inches, **kwargs)
    129 
    130     bytes_io = BytesIO()
--> 131     fig.canvas.print_figure(bytes_io, **kw)
    132     data = bytes_io.getvalue()
    133     if fmt == 'svg':

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/backend_bases.pyc in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
   2210                     orientation=orientation,
   2211                     dryrun=True,
-> 2212                     **kwargs)
   2213                 renderer = self.figure._cachedRenderer
   2214                 bbox_inches = self.figure.get_tightbbox(renderer)

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in print_png(self, filename_or_obj, *args, **kwargs)
    515 
    516     def print_png(self, filename_or_obj, *args, **kwargs):
--> 517         FigureCanvasAgg.draw(self)
    518         renderer = self.get_renderer()
    519         original_dpi = renderer.dpi

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in draw(self)
    435             # if toolbar:
    436             #     toolbar.set_cursor(cursors.WAIT)
--> 437             self.figure.draw(self.renderer)
    438             # A GUI class may be need to update a window using this draw, so
    439             # don't forget to call the superclass.

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/figure.pyc in draw(self, renderer)
   1491 
   1492             mimage._draw_list_compositing_images(
-> 1493                 renderer, self, artists, self.suppressComposite)
   1494 
   1495             renderer.close_group('figure')

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/image.pyc in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    139     if not_composite or not has_images:
    140         for a in artists:
--> 141             a.draw(renderer)
    142     else:
    143         # Composite any adjacent images together

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/axes/_base.pyc in draw(self, renderer, inframe)
   2633             renderer.stop_rasterizing()
   2634 
-> 2635         mimage._draw_list_compositing_images(renderer, self, artists)
   2636 
   2637         renderer.close_group('axes')

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/image.pyc in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    139     if not_composite or not has_images:
    140         for a in artists:
--> 141             a.draw(renderer)
    142     else:
    143         # Composite any adjacent images together

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/image.pyc in draw(self, renderer, *args, **kwargs)
    592         else:
    593             im, l, b, trans = self.make_image(
--> 594                 renderer, renderer.get_image_magnification())
    595             if im is not None:
    596                 renderer.draw_image(gc, l, b, im)

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/image.pyc in make_image(self, renderer, magnification, unsampled)
    840         return self._make_image(
    841             self._A, bbox, transformed_bbox, self.axes.bbox, magnification,
--> 842             unsampled=unsampled)
    843 
    844     def _check_unsampled_image(self, renderer):

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/image.pyc in _make_image(self, A, in_bbox, out_bbox, clip_bbox, magnification, unsampled, round_to_pixel_border)
    520                 alpha_channel = output[:, :, 3]
    521                 alpha_channel[:] = np.asarray(
--> 522                     np.asarray(alpha_channel, np.float32) * out_alpha * alpha,
    523                     np.uint8)
    524 

ValueError: operands could not be broadcast together with shapes (218,218) (100,100)

Expected outcome

Matplotlib version

  • Operating system:
  • Matplotlib version: 2.2.3
  • Matplotlib backend (print(matplotlib.get_backend())): TkAgg
  • Python version: 2.7.16
  • Jupyter notebook version (if applicable): 5.7.8
  • Other libraries: Numpy version: 1.16.5

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.