Skip to main content
 首页 » 编程设计

python之使用 matplotlib 保存为 svg 时如何设置 miterlimit

2024年10月17日6mq0036

在将 matplotlib 图保存为 svg 时是否有设置斜接限制?我想以编程方式解决这个错误:https://bugs.launchpad.net/inkscape/+bug/1533058 而我必须在“.svg”文本文件中手动更改它。

请您参考如下方法:

此参数定义为 'stroke-miterlimit': '100000' 并在 backend_svg.py 中进行了硬设置。 matplotlibrc 中没有这样的参数,因此不太可能使用样式表进行自定义。

我使用下面的代码来解决这个问题:

def fixmiterlimit(svgdata, miterlimit = 10): 
    # miterlimit variable sets the desired miterlimit 
    mlfound = False 
    svgout = "" 
    for line in svgdata: 
        if not mlfound: 
             # searches the stroke-miterlimit within the current line and changes its value 
             mlstring = re.subn(r'stroke-miterlimit:([0-9]+)', "stroke-miterlimit:" + str(miterlimit), line) 
        if mlstring[1]: # use number of changes made to the line to check whether anything was found 
            mlfound = True 
            svgout += mlstring[0] + '\n' 
        else: 
            svgout += line + '\n' 
    else: 
        svgout += line + '\n' 
return svgout 

然后像这样调用它(使用来自 post 的技巧):

import StringIO 
... 
imgdata = StringIO.StringIO() # initiate StringIO to write figure data to 
# the same you would use to save your figure to svg, but instead of filename use StringIO object 
plt.savefig(imgdata, format='svg',  dpi=90, bbox_inches='tight') 
imgdata.seek(0)  # rewind the data 
svg_dta = imgdata.buf  # this is svg data 
 
svgoutdata = fixmiter(re.split(r'\n', svg_dta)) # pass as an array of lines 
svgfh = open('figure1.svg', 'w') 
svgfh.write(svgoutdata) 
svgfh.close() 

代码基本上是在将 SVG 输出写入文件之前更改 stroke-miterlimit 参数。为我工作。