What wizardry is being used to display Matplotlib color maps in an ipython console?

Viewed 34

I am working with Matplotlib color maps, and I also happen to be working with the Spyder IDE, which has an ipython console.

Screen shot of ipython console in Spyder showing Matplotlib color map rendering as a graph

As you can see from the screen shot, the ipython console showed me a graphical representation of the color map object. This was unexpected and very helpful.

Normally I expect to see a string representation of an object, as you might see from the print() function call. Function calls to print() and repr() are shown, and they produce text, as is more typical.

I would like my own code to output this graphical representation when it is generating output. I have been poking through the matplotlib.colors.Colormap internals, and so far I haven't been able to figure out how. What is ipython doing? How can I do the same?

Thanks!

3 Answers

This rather seems like a ipython/jupyter feature. ipython detects the object and produces automatically a plot to preview the colormap.

Here using jupyter:

cmap preview

IPython looks if an object has a _repr_html_; if so, it calls it and displays the output as HTML. Here's an example (I ran this in Jupyter but it works the same as long as you're running IPython):

enter image description here

class MyCoolObject:
    def _repr_html_(self):
        return ("<h1>hello!</h1> <p>this is some html </p>"
                "I can even put images:"
                "<img src='https://upload.wikimedia.org/wikipedia"
                "/commons/thumb/3/38/Jupyter_logo.svg"
                "/44px-Jupyter_logo.svg.png'></img>")

MyCoolObject()

To add on to Eduardo's answer, from everything I've read adding a _repr_html_ method should make iPython display the object when you type it into the console. I also use spyder though, and could not get it to work the way I expected. This simple wrapper class should allow you to display any html:

class displayedHTML:
    def __init__(self, html):
        self.html = html

    def _repr_html_(self):
        return self.html

But as you can see it does not work for me, instead showing the (implicitly defined) __repr__ of the class.

In [2]: obj = displayedHTML("<h1>" + "hello world" + "</h1>")

In [3]: obj
Out[3]: <__main__.displayedHTML at 0x1e8cda8f0d0>

I was not able to find the reason why this does not work, but I found a workaround if you just want to display a matplotlib colormap in the console from code (like I did).

Since know the matplotlib object works correctly, we can just give it to the ipython display function:

from IPython.display import display #Included without import since IPython 5.4 and 6.1
viridis = matplotlib.cm.get_cmap('viridis')
display(viridis)

And for me this works... not_allowed_to_insert_pictures_yet.jpg

Hope this helps!

Related