将多个EPS图像加载到matplotlib子图

时间:2015-03-25 19:42:02

标签: python image python-2.7 matplotlib

我试图使用subplot命令绘制多个eps图像和散点图,但似乎无法获得imshow命令来执行此操作。这是一个例子:

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')

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

简单的答案:将* .eps保存为* .png等光栅格式

答案很长但是如果你喜欢它可扩展且能够修改外观属性,那么对我来说有用的东西就是使用xml.dom库导入.svg文件。您可以使用Inkscape将eps文件另存为.svg。

将它拆开并在matplotlib中重新组合:

这是一个可能想要重绘的svg元素的示例:

<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 "/>

首先,将svg作为顶点和外观属性列表拉入。您可以根据需要提取少量或多种外观属性:

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']]

然后,在matplotlib中重新构建路径

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