Search code examples
pythonunicodeencodingchartscairoplot

Charts with proper unicode support


I want to create simple charts like pies and bars in python.

I tried out CairoPlot and pycha. Both look amazing, but they seem not to be able to handle unicode characters properly.

CairoPlot.pie_plot(name='test.png', width=800, height=600, 
                   data={'eins':100, 'zwei':48, 'drei':90, 'vier':98,u'fünf':187})

result in fünf instead of fünf.

Is there an easy to use module with proven support for unicode? or did you make CairoPlot or pycha display the unicodes correctly?

I prefer in-house solution, so google chart is not what I want.

edit

ironfroggy's answer made me try this

CairoPlot.pie_plot(name='test.png', width=800, height=600, 
                   data={'eins':100, 'zwei':48, 'drei':90, 'vier':98,'f\xc3\xbcnf':187})

this works.

What is a safe way to convert unicode-strings to ascii-strings with escaped non-ascii characters?

edit 2

u'fünf'.encode('latin-1')

does the trick. Thanks!

edit 3

for pycha it worked in the same way

dataSet = (                                
     ('dataSet 1', ((0, 1), (1, 3), (2, 2.5))),
     ('dataSet 2', ((0, 2), (1, 4), (2, 3))),
     (u'dataSet Ü'.encode('latin-1'), ((0, 5), (1, 1), (2, 0.5))),
)
chart = pycha.bar.VerticalBarChart(surface)
chart.addDataset(dataSet)                  
chart.render()
surface.write_to_png('output.png')

Solution

  • Be careful including non-ASCII directly in your source. Are you including an encoding hint in your source?

    #!/usr/bin/env python
    # -*- encoding: utf-8 -*-
    

    And, of course, are you sure your editor is properly saving the file in the encoding you think it is? The safest bet is still to keep source in ASCII and to do unicode string literals with escaped non-ASCII characters (like \UXXXX where XXXX is your codepoint).