user2483176
user2483176

Reputation: 317

load multiple EPS images to matplotlib subplot

I am trying to plot multiple eps images alongside scatter plots using the subplot command but can't seem to get the imshow command to do this. Here is an example:

fig = figure()
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
ax4 = fig.add_subplot(2,2,4)

ax1.scatter(x,y)
ax2.imshow('image.eps')
ax3.scatter(x,y)
ax4.imshow('image2.eps')

Any suggestions?

Upvotes: 1

Views: 2425

Answers (1)

Robert Beach
Robert Beach

Reputation: 11

The simple answer: save your *.eps as a raster format like *.png

A long answer : However if you like it scale-able and theh ability to modify the appearance properties, something that worked for me involved importing an .svg file using the xml.dom library. You can use Inkscape to save an eps file as an .svg.

Take it apart and put it back together in matplotlib:

This is an example of an svg element one might want to redraw:

<polygon id="SimpleShape" fill="none" stroke="#231F20" stroke-miterlimit="10" points="101.3,20.5 101.3,86.5 158.5,86.5 158.5,126.9 209.5,126.9 209.5,20.5 "/>

First, pull in the svg as lists of vertices and appearance properties. You can pull as few or as many appearance attributes as you'd like:

from xml.dom import minidom
from matplotlib.path import Path
import matplotlib.patches as patches

doc = minidom.parse('path_to_svg_file.svg')


# pull the objects you want to re-plot into a dictionary 
# in my case those were any polygons 

gons = {}
for polygon in doc.getElementsByTagName('polygon'):
    pts = polygon.getAttribute('points').split(' ')
    label = polygon.getAttribute('id')

    gons[label] = {}
    gons[label]['pts'] = []

    # build list of tuples for each point - [(x1,y1),(x2,y2)...(xn,yn)]
    for pt in pts:
        if len(pt) > 0:
            gons[label]['pts'].append(tuple([float(val) for val in pt.split(',')]))

    # close the path by appending the last point if you need to you could also        
    # get other information from the polygon such as color and line weight

    gons[label]['pts'].append(gons[label][0])

    # note the y value of a point must be inverted from inkscape*

    gons[label]['pts'] = [(pt[0],-1*pt[1]) for pt in gons[label]['pts']]

Then, re-build the path in matplotlib

for label in gons:
    path = Path(gons[label]['pts']
    patch = patches.PathPatch(path, facecolor=(0,0,0), lw=1)
    ax.add_patch(patch)

Upvotes: 1

Related Questions