由于Matplotlib图例中的负数,IPython笔记本出现unicodedecoderror

2024-04-29 02:47:59 发布

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

在一个小IPython笔记本中遇到一个奇怪的错误:https://gist.github.com/goulu/ba518d1a0a5267c0d3f3

在为IPython笔记本(2.7内核)生成svg绘图的方法repr帴svg方法中

plt.legend()
savefig(output, format='svg')

生成类似于 <!-- \xe2\x88\x925 -->

对于图例中的“-5”,这将通过IPython/Jupyter客户端在JSON中导致UnicodeDecodeError

虫子在哪里?在我的代码中,在Matplotlib中还是在IPython中?在


Tags: 方法httpssvggithubcom绘图错误ipython
2条回答

您的数据似乎有一些不支持的字符。你可以试试

data= unicode(output.getvalue(), errors='replace')

或者

^{pr2}$

通过将.decode('utf-8')添加到\u repr_svg\方法的末尾来解决:

def _repr_svg_(self):
    fig, ax = plt.subplots()
    ax.plot(self.x,self.y)
    plt.legend()

    from io import BytesIO
    output = BytesIO()
    fig.savefig(output, format='svg')
    data=output.getvalue() # .encode('utf-8') doesn't change anything
    plt.close(fig)
    return data.decode('utf-8')

很抱歉吵闹了:-/

相关问题 更多 >