Generating pie chart with Python and Google Chart API

Posted on Updated on

Chart

I recently discovered Google Chart API. From URLs it is able to generate image files with plots of different sorts, e.g., line plots, pie charts or even QR codes. The pie chart here was generated with the following code:

du -sk /usr/* > stats.txt ; python -c "d = open('stats.txt').read().split();  s = sum(map(float, d[0::2]));  print('http://chart.apis.google.com/chart?cht=p&chd=t:' +  ','.join(map(lambda x : str(int(float(x)/s*100)),d[0::2])) +  '&chs=600x300&chl=' + '|'.join(d[1::2]));"

Copy and pasting the returned URL into a Web-browser will show the Google-generated pie chart as PNG. Alternatively one could let Python download the file by modifying the code to use ‘urllib.urlretrieve()’.

For the data in the ‘chd’ parameter it seems that one needs to indicate the percentage.

There is also a module called pycha, which I haven’t tried.

Advertisements

2 thoughts on “Generating pie chart with Python and Google Chart API

    pankaj said:
    August 26, 2015 at 8:58 am

    where is full code. why do you make my fool. i am searching a good tutorial for pie chart but you all are sucker

    Finn Årup Nielsen responded:
    August 26, 2015 at 9:09 am

    Thanks for your comment. There was a missing “;”. The full code is right there. It is just one line and can be executed on a Linux system. The “du” command collects file system information and saves it to the “stats.txt” file. The small Python program just reformats the data to the format of the Google Chart API.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s