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

In order to send metrics, logs, images or parameters to Neptune, you need to instantiate Neptune Context object first:

1
2
3
import neptune

ctx = neptune.Context()

Step 2

Create matplotlib figure:

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

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

Step 3

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 4

Send it to Neptune image channel.

1
2
3
ctx.channel_send('distplot', neptune.Image(name='distplot iteration',
                                           description='distribution of random numbers',
                                           data=pil_image))

Step 5

Explore it in the browser:

image

image

See also