pythonpygal

Why does my code not return an error but still doesn't create a window?


When I run this code it doesn't return error but doesn't create a window. Somebody please help.

import pygal as pyg

line_chart = pyg.HorizontalBar()
line_chart.title = 'Friends favorite pizza topping'
line_chart.add('olives', 24)
line_chart.add('TOMATO', 32)
line_chart.add('pepperoni', 42)
line_chart.add('mushroom', 0.5)
line_chart.add('other', 1.5)
line_chart.render()

Solution

  • It generates SVG data which you can assign to variable

     data = line_chart.render()
    

    and use to embed in HTML or to save in file

     with open('image.svg', 'wb') as fh:  # need binary mode
         fh.write(data)
    

    or

     line_chart.render_to_file('image.svg')
    
     line_chart.render_to_png('image.png')
    

    and later you can open it in browser or viewer.

    If you want to see it at once in web browser then you need

     line_chart.render_in_browser()
    

    There are other render_.... to generate response for Flask and Django, etc.


    Maybe if you use render() in jupyter notebook or Google Colab (which run in web browser) then it will display it at once.


    import pygal as pyg
    
    line_chart = pyg.HorizontalBar()
    line_chart.title = 'Friends favorite pizza topping'
    line_chart.add('olives', 24)
    line_chart.add('TOMATO', 32)
    line_chart.add('pepperoni', 42)
    line_chart.add('mushroom', 0.5)
    line_chart.add('other', 1.5)
    
    data = line_chart.render(pretty_print=True)
    print(data.decode())
    
    with open('image.svg' 'wb') as fh:
        fh.write(data)
        
    #line_chart.render_to_file('image.svg')
    #line_chart.render_to_png('test.png')
    
    line_chart.render_in browser()