title: Overlaying matplotlib commands on existing Cairo image surface/context
body: <p>I have a diagram created from a SVG file and loaded in using the <a href="https://github.com/Kozea/CairoSVG" rel="nofollow">cairosvg</a> library.</p>
  
  <p>I want to further enhance this diagram with additional overlaid plots defined programatically via direct matplotlib commands.</p>
  
  <p>I'm trying to do this in memory and <em>not</em> to write out to file and reload in. Only saving the final file.</p>
  
  <p>However, it's proving difficult to <em>combine</em> the existing cairo with that which is being rendered by matplotlib. I thought that <a href="http://sixdegrees.hu/blog/2010/07/plotting-igraph-graphs-in-matplotlib/" rel="nofollow">this was a potential solution</a>, but not sure.</p>
  
  <p>Simplified example:</p>
  
  <pre><code>import matplotlib
  matplotlib.use('Cairo') # Make sure here that our figures will use Cairo!
  from cairosvg import surface
  from cairosvg import parser
  import matplotlib.pyplot as plt
  import matplotlib.image as img 
  import numpy as np
  
  SVG='\
  &lt;svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="500" height="500"&gt;\
  &lt;rect id="arena" x="10" y="10" width="480" height="480" fill="#ff5555" fill-opacity="0.5"/&gt;\
  &lt;/svg&gt;\
  '
  
  svg = parser.Tree(bytestring=SVG)
  
  surf = surface.PNGSurface(svg,None,1)
  #surf.cairo.write_to_png("test-svg.png") # Can do this to see svg render to file
  surf.finish() # Required?
  ctx = surf.context # Can get the context here fine..
  
  fig = plt.imshow(ctx) # &lt;----- MAGIC REQUIRED HERE ABOUTS
  #fig = plt.figure() # This works like a normal plot - but no svg
  
  ax = fig.gca() # Create some overlay data
  x = np.array(np.random.randn(100))
  y = np.array(np.random.randn(100))
  ax.plot(x,y)
  
  plt.savefig("test-final.png") # Save svg &amp; overlay plot
  </code></pre>
  
  <p><strong>EDIT:</strong> also been trying the following, based on earlier above link. Still no joy though.</p>
  
  <pre><code>from matplotlib.artist import Artist
  
  class SurfArtist(Artist):
    def __init__(self,surf):
      Artist.__init__(self)
      self._surf = surf
  
    def draw(self,renderer):
      from matplotlib.backends.backend_cairo import RendererCairo
      if not isinstance(renderer, RendererCairo):
        raise TypeError("backend not supported")
      ctx = renderer.gc.ctx if hasattr(renderer, "gc") else renderer.ctx
      self._surf.context = ctx
      self._surf.cairo.show_page()
  
  ...
  
  fig = plt.figure()
  ax = fig.gca()
  surf_artist = SurfArtist(surf)
  surf_artist.set_zorder(float('inf'))
  ax.artists.append(surf_artist)
  </code></pre>