Rpy2 and drawing pie diagram

Here is code that I come up with for drawing a pie diagram using rpy2. The function takes two lists. Function takes two lists: data contains frequencies and labels labels. The argument title set the title text of chart. Radius sets the radius of pie (max 1.0). Font size 1 is default, 1.5 is 50% bigger, 0.5 is 50% smaller. If file name is provided the chart will be saved to png file. Radius, font_size, and file name are optional parameters.

import rpy2.robjects as robjects
from rpy2.robjects.packages import importr

def draw_pie(data, labels, title, radius=0.8, font_size=1.0, file_name=None):

    total = 0
    for x in data: total = total + x

    labels_with_percentages = []
    for td, tl in zip(data, labels):
        percentage = 100.0 * float(td)/float(total)
        labels_with_percentages.append("%s %.1f%%" % (tl, percentage))

    l = robjects.StrVector(labels_with_percentages)
    d = robjects.IntVector(data)

    grdevices = importr('grDevices')
    if file_name:
        grdevices.png(file_name)
    font = robjects.r['par'](cex=font_size)
    robjects.r.pie(d,l, main=title, radius=radius)
    if file_name:
        grdevices.dev_off()

To use this we can do:

draw_pie([10,8],["Male", "Female"], "Sex", font_size=1.5, file_name="chart.png")

Published by lankoski

Petri Lankoski, D.Arts, is a Associate Professor in Game Studies at the school of Communication, Media and IT at the Södertörn University, Sweden. His research focuses on game design, game characters, role-playing, and playing experience. Petri has been concentrating on single-player video games but researched also (multi-player) pnp and live-action role-playing games. This blog focuses on his research on games and related things.

3 thoughts on “Rpy2 and drawing pie diagram

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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: