How to send matplotlib chart to Neptune?

Problem

How to log charts generated in matplotlib, like confusion matrix or distribution in Neptune?

Solution

Step 1

Create matplotlib figure:

1
2
3
4
5
import matplotlib.pyplot as plt
import seaborn as sns

fig = plt.figure()
sns.distplot(np.random.random(100))

Step 2

Convert your matplotlib figure object into PIL image.

For example you could use the following function, taken from here, and adjusted slightly:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import numpy as np
from PIL import Image

def fig2pil(fig):
    fig.canvas.draw()

    w, h = fig.canvas.get_width_height()
    buf = np.fromstring(fig.canvas.tostring_argb(), dtype=np.uint8)
    buf.shape = (w, h, 4)
    buf = np.roll(buf, 3, axis=2)

    w, h, d = buf.shape
    return Image.frombytes("RGBA", (w, h), buf.tostring())

pil_image = fig2pil(fig)

Step 3

Send it to Neptune!

1
2
neptune.create_experiment()
neptune.send_image('distplot', pil_image)

Step 5

Explore it in the browser:

image

image

See also