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

Time:08-08

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!

CodePudding user response:

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

CodePudding user response:

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()
  • Related