Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1cfb18b

Browse files
committed
Created _repr_png_ and _repr_html_ for Colormap objects.
1 parent ec0132f commit 1cfb18b

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

lib/matplotlib/colors.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,14 @@
6565
.. _xkcd color survey: https://xkcd.com/color/rgb/
6666
"""
6767

68+
import base64
6869
from collections.abc import Sized
6970
import functools
71+
import io
7072
import itertools
7173
from numbers import Number
7274
import re
75+
from PIL import Image
7376

7477
import numpy as np
7578
import matplotlib.cbook as cbook
@@ -691,6 +694,25 @@ def reversed(self, name=None):
691694
"""
692695
raise NotImplementedError()
693696

697+
def _repr_png_(self):
698+
"""Generate a PNG representation of the Colormap."""
699+
IMAGE_SIZE = (400, 50)
700+
X = np.tile(np.linspace(0, 1, IMAGE_SIZE[0]), (IMAGE_SIZE[1], 1))
701+
pixels = self(X, bytes=True)
702+
png_bytes = io.BytesIO()
703+
Image.fromarray(pixels).save(png_bytes, format='png')
704+
return png_bytes.getvalue()
705+
706+
def _repr_html_(self):
707+
"""Generate an HTML representation of the Colormap."""
708+
png_bytes = self._repr_png_()
709+
png_base64 = base64.b64encode(png_bytes).decode('ascii')
710+
return ('<strong>' + self.name + '</strong>' +
711+
'<img ' +
712+
'alt="' + self.name + ' color map" ' +
713+
'title="' + self.name + '"' +
714+
'src="data:image/png;base64,' + png_base64 + '">')
715+
694716

695717
class LinearSegmentedColormap(Colormap):
696718
"""

0 commit comments

Comments
 (0)