简体   繁体   中英

UnicodeDecodeError in IPython Notebook because of negative numbers in Matplotlib legend

Encountered a strange error shown in a small IPython Notebook here : https://gist.github.com/goulu/ba518d1a0a5267c0d3f3

in the method repr_svg method that generates a svg plot for IPython Notebook ( 2.7 kernel )

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

generates content like <!-- \\xe2\\x88\\x925 -->

for "-5" in the legend, which causes a UnicodeDecodeError in JSON via IPython/Jupyter client

Where is the bug ? In my code, in Matplotlib or in IPython ?

It seems you data have some not supported character. you could try

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

or

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

unicode('\xe2\x88\x925',errors= 'ignore')
output:
u'5'

solved by adding a .decode('utf-8') at the end of the _repr_svg_ method:

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

sorry for the noise :-/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM