Search code examples
pythonmatplotliborg-mode

Shading behind the plot in org-mode babel and matplotlib


Consider the following python code block in org-mode with babel:

#+begin_src python :results none
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
graylevel = 0.75
mpl.rc('figure', facecolor = (graylevel, graylevel, graylevel), edgecolor ='r')
X = np.linspace(0, 7, 1024)
plt.plot(X, np.sin(X))
plt.plot(X, np.cos(X))
plt.draw()
plt.show()
#+end_src]

In a pop-up window, this produces a plot with a gray background

enter image description here

but, when putting the plot in a file, again in org-mode (only the last couple of lines are different)

#+begin_src python :results file
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
graylevel = 0.75
mpl.rc('figure', facecolor = (graylevel, graylevel, graylevel), edgecolor ='r')
X = np.linspace(0, 7, 1024)
plt.plot(X, np.sin(X))
plt.plot(X, np.cos(X))
plt.draw()
plt.savefig('test.png')
return 'test.png'
#+end_src

#+RESULTS:
[[file:test.png]]

The gray background is gone

enter image description here

I do need the gray backgrounds for exporting my plots from org-mode because I need the plots set off from the surrounding document.

I don't know if this is an issue with matplotlib, with org-mode, with python, with my machine, or with me. I hope someone can repro this example or perhaps just knows the answer.


Solution

  • I don't think this is an issue with org-mode, but is the same issue discussed here.

    This is the solution to your troubles:

    plt.savefig('test.png', facecolor=(graylevel, graylevel, graylevel))