In [1]:
!mkdir -p /tmp/embed-matplotlib

In [2]:
%%file /tmp/embed-matplotlib/plot.cc
#include <Python.h>

int main() {
  Py_Initialize();
  PyRun_SimpleString("import numpy as np");
  PyRun_SimpleString("import matplotlib.pyplot as plt");

  PyRun_SimpleString("x = np.linspace(0, 10, 100)");
  PyRun_SimpleString("plt.plot(x, np.sin(x))");
  PyRun_SimpleString("plt.savefig('/tmp/figure.png')");
  Py_Finalize();
  return 0;
}


Overwriting /tmp/embed-matplotlib/plot.cc

In [3]:
%%file /tmp/embed-matplotlib/Makefile
#!/usr/bin/make -f
# -*- mode:makefile -*-

LDFLAGS = -lpython2.7
CXXFLAGS = -I/usr/include -I/usr/include/python2.7/
TARGET = $(patsubst %.cc, %, $(wildcard *.cc))

all: $(TARGET)

clean:
	$(RM) $(TARGET) *.o *~


Overwriting /tmp/embed-matplotlib/Makefile

In [4]:
!make -C /tmp/embed-matplotlib/ clean all


make: Entering directory '/tmp/embed-matplotlib'
rm -f  plot *.o *~
g++ -I/usr/include -I/usr/include/python2.7/  -lpython2.7  plot.cc   -o plot
make: Leaving directory '/tmp/embed-matplotlib'

In [5]:
!/tmp/embed-matplotlib/plot

In [12]:
from IPython.display import Image
Image(filename='/tmp/figure.png')


Out[12]: