11
$\begingroup$

How to display images inside Mathematica with matplotlib.

enter image description here

A new window is generated by default, but is it possible to display the picture directly in the notebook?

Like this:

enter image description here

related: How to display images and plots from ExternalEvaluator?

$\endgroup$
  • 3
    $\begingroup$ What advantage would this have over generating those plots in native MMA code? $\endgroup$ – MarcoB Dec 11 '19 at 16:20
  • $\begingroup$ @MarcoB I assume for comparison reasons? (Also, of course some people might like ugly Python code and clunky graphics...) $\endgroup$ – Anton Antonov Dec 18 '19 at 11:38
10
$\begingroup$

Seems to be able to embed images by converting to png.

import io
from PIL import Image
import matplotlib.pyplot as plt


def show_plt(plot):
    buf = io.BytesIO()
    plot.savefig(buf, transparent=True, format='png')
    buf.seek(0)
    im = Image.open(buf).convert("RGBA")
    buf.close()
    return im

enter image description here

In fact, matplotlib can export svg, but wolfram does not support importing svg, so there is no way to get vector graphics.

Note that this function works for all libraries that depend on matplotlib, like seaborn:

enter image description here

|improve this answer|||||
$\endgroup$
  • 1
    $\begingroup$ Will this work on any raster image format that Python can save and Wolfram Language can import? Or did you try a few raster formats and only PNG worked? $\endgroup$ – Edmund Dec 17 '19 at 23:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.