Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions doc/users/next_whats_new/colormap_repr.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
IPython representations for Colormap objects
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The `matplotlib.colors.Colormap` object now has image representations for
IPython / Jupyter backends. Cells returning a color map on the last line will
display an image of the color map.
32 changes: 32 additions & 0 deletions lib/matplotlib/colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,17 @@
.. _xkcd color survey: https://xkcd.com/color/rgb/
"""

import base64
from collections.abc import Sized
import functools
import io
import itertools
from numbers import Number
import re
from PIL import Image
from PIL.PngImagePlugin import PngInfo

import matplotlib as mpl
import numpy as np
import matplotlib.cbook as cbook
from matplotlib import docstring
Expand Down Expand Up @@ -691,6 +696,33 @@ def reversed(self, name=None):
"""
raise NotImplementedError()

def _repr_png_(self):
"""Generate a PNG representation of the Colormap."""
IMAGE_SIZE = (400, 50)
X = np.tile(np.linspace(0, 1, IMAGE_SIZE[0]), (IMAGE_SIZE[1], 1))
pixels = self(X, bytes=True)
png_bytes = io.BytesIO()
title = self.name + ' color map'
author = f'Matplotlib v{mpl.__version__}, https://matplotlib.org'
pnginfo = PngInfo()
pnginfo.add_text('Title', title)
pnginfo.add_text('Description', title)
pnginfo.add_text('Author', author)
pnginfo.add_text('Software', author)
Image.fromarray(pixels).save(png_bytes, format='png', pnginfo=pnginfo)
return png_bytes.getvalue()

def _repr_html_(self):
"""Generate an HTML representation of the Colormap."""
png_bytes = self._repr_png_()
png_base64 = base64.b64encode(png_bytes).decode('ascii')
return ('<strong>' + self.name + '</strong>' +
'<img ' +
'alt="' + self.name + ' color map" ' +
'title="' + self.name + '"' +
'style="border: 1px solid #555;" ' +
'src="data:image/png;base64,' + png_base64 + '">')


class LinearSegmentedColormap(Colormap):
"""
Expand Down
13 changes: 13 additions & 0 deletions lib/matplotlib/tests/test_colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -1135,3 +1135,16 @@ def test_hex_shorthand_notation():
def test_DivergingNorm_deprecated():
with pytest.warns(cbook.MatplotlibDeprecationWarning):
norm = mcolors.DivergingNorm(vcenter=0)


def test_repr_png():
cmap = plt.get_cmap('viridis')
png = cmap._repr_png_()
assert len(png) > 0


def test_repr_html():
cmap = plt.get_cmap('viridis')
html = cmap._repr_html_()
assert len(html) > 0
assert cmap.name in html