diff --git a/lib/matplotlib/animation.py b/lib/matplotlib/animation.py index 47f2f0f9515b..2be61284073a 100644 --- a/lib/matplotlib/animation.py +++ b/lib/matplotlib/animation.py @@ -492,8 +492,15 @@ def grab_frame(self, **savefig_kwargs): buf = BytesIO() self.fig.savefig( buf, **{**savefig_kwargs, "format": "rgba", "dpi": self.dpi}) - self._frames.append(Image.frombuffer( - "RGBA", self.frame_size, buf.getbuffer(), "raw", "RGBA", 0, 1)) + im = Image.frombuffer( + "RGBA", self.frame_size, buf.getbuffer(), "raw", "RGBA", 0, 1) + if im.getextrema()[3][0] < 255: + # This frame has transparency, so we'll just add it as is. + self._frame.append(im) + else: + # Without transparency, we switch to RGB mode, which converts to P mode a + # little better if needed (specifically, this helps with GIF output.) + self._frames.append(im.convert("RGB")) def finish(self): self._frames[0].save(