Skip to content

Instantly share code, notes, and snippets.

@bbarrilleaux
Last active December 31, 2015 09:49
Show Gist options
  • Save bbarrilleaux/7969742 to your computer and use it in GitHub Desktop.
Save bbarrilleaux/7969742 to your computer and use it in GitHub Desktop.
Python code to graph my tooth flossing habits using both RPy and Matplotlib.
import numpy as np
import pandas as pd
import matplotlib.pyplot as pyplot
import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
data = pd.read_csv('FlossChart.csv', usecols = [0, 1],
parse_dates = True)
data['daynumber'] = data.date.map(lambda x:
pd.to_datetime(x).weekday())
data['weekday'] = data.date.map(lambda x:
pd.to_datetime(x).strftime("%a"))
fractions = []
names = []
for day in range(0, 7):
relevantrows = data[data['daynumber'] == day]
names.append(relevantrows.weekday.iloc[1])
fractions.append(relevantrows['flossed'].mean())
#First let's plot it using pyplot.
pyplot.bar(np.arange(1, 8, 1), fractions)
pyplot.title('Flossing breakdown by day of the week')
pyplot.ylabel('Fraction of days flossed')
pyplot.xticks(np.arange(1.4, 8.4, 1), names)
pyplot.savefig('Flosschart-py.png')
#Now let's do it in RPy.
r = robjects.r
rfractions = robjects.FloatVector(fractions)
rdays = robjects.StrVector(names)
rfractions.names = rdays
grdevices = importr('grDevices')
grdevices.png(file = "Flosschart-r.png",
width = 512, height = 512)
robjects.r.barplot(rfractions, ylim = robjects.r.c(0, 1),
main = "Flossing breakdown by day of the week",
ylab = "Fraction of days flossed")
grdevices.dev_off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment