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

2024-06-30 12:55:51 发布

您现在位置:Python中文网/ 问答频道 /正文

在将matplotlib绘图保存到svg时,是否有必要设置miterlimit?我想通过编程来解决这个问题:https://bugs.launchpad.net/inkscape/+bug/1533058 而我必须在“.svg”文本文件中手动更改此内容。在


Tags: httpssvg绘图内容netlaunchpadmatplotlib编程
2条回答

感谢drYG的回答和aeolus的问题。我有一个类似的问题,由于这个inkscape错误和缺乏一个简单的方法来更改matplotlib中的设置。然而,drYG的答案似乎并不适用于python3。我已经对它进行了更新,并修改了一些可能的拼写错误(与python版本无关)。希望这能为别人节省一些时间,因为我努力弥补我的损失!在

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'
    return svgout

import io, re
imgdata = io.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.gca()
plt.savefig(imgdata, format='svg',  dpi=90, bbox_inches='tight')
imgdata.seek(0)  # rewind the data
svg_dta = imgdata.getvalue()  # this is svg data
svgoutdata = fixmiterlimit(re.split(r'\n', svg_dta)) # pass as an array of lines
svgfh = open('test.svg', 'w')
svgfh.write(svgoutdata)
svgfh.close()

此参数被定义为'stroke-miterlimit': '100000',并且是在后端硬设置的_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的技巧):

^{pr2}$

基本上,在写入SVG文件之前,先将stroke参数写入SVG文件。为我工作。在

相关问题 更多 >