Advertisement
user_137

ggplot

Mar 16th, 2014
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.61 KB | None | 0 0
  1. import pandas as pd
  2. import random
  3. import matplotlib as pl
  4. import pylab
  5. from pandas import DataFrame
  6. from ggplot import *
  7.  
  8.  
  9. def flipTrials(minExp, maxExp, numTrials):
  10.     """Assumes minExp and maxExp positive integers; minExp < maxExp
  11.    Plots results of 2**minExp to 2**maxExp coin flips"""
  12.  
  13.     cols = ['x', 'ratio_means', 'ratio_stdvs', 'ratio_coeffvar',
  14.             'diffs_means', 'diffs_stdvs', 'diffs_coeffvar']
  15.     df = DataFrame(index=range(minExp, maxExp + 1), columns=cols)
  16.     for i in df.index:
  17.         numFlips = 2**i
  18.         numHeads = np.random.randint(0, 2, [numTrials, numFlips]).sum(1)
  19.         numTails = np.ones(numTrials)*numFlips - numHeads
  20.         ratio = numHeads / numTails
  21.         diffs = abs(numHeads - numTails)
  22.         df.x[i] = numFlips
  23.         df.ratio_means[i] = ratio.mean()
  24.         df.ratio_stdvs[i] = ratio.std()
  25.         if df.ratio_means[i] > 0:
  26.             df.ratio_coeffvar[i] = df.ratio_stdvs[i] / df.ratio_means[i]
  27.         df.diffs_means[i] = diffs.mean()
  28.         df.diffs_stdvs[i] = diffs.std()
  29.         if df.diffs_means[i] > 0:
  30.             df.diffs_coeffvar[i] = df.diffs_stdvs[i] / df.diffs_means[i]
  31.  
  32.     # for faceting create a dataframe with all columns stacked and indexed by colname
  33.     dfm = pd.melt(df[['x', 'ratio_means', 'ratio_stdvs', 'diffs_means', 'diffs_stdvs',
  34.                      'ratio_coeffvar', 'diffs_coeffvar']], id_vars='x')
  35.     print ( ggplot(dfm, aes(x='x', y='value', colour='variable'))
  36.             +geom_line() + scale_x_log() + facet_wrap('variable') )
  37.     return df, dfm
  38.  
  39. random.seed(0)
  40. df, dfm = flipTrials(2, 10, 2)
  41. print 'Test:\n ', df[-5:]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement