view talk/code/plots.py @ 48:1baa6b0a7199

move duplicate code into function this changed the dimensions of the generated image slightly
author Jordi Gutiérrez Hermoso <jordigh@octave.org>
date Sun, 15 May 2016 00:20:01 -0400
parents 7887a0b32539
children 4a669a51f49c
line wrap: on
line source

import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import numpy as np

def boxhistplot(data, fig=None, rect=None, xticks=None, colour=None,
                bins=None, title=None):
    data_stats = cbook.boxplot_stats(data)

    left, bottom, width, height = rect
    histheight = 0.75*height
    boxheight = 0.25*height

    # setup the figure and axes
    bpAx = fig.add_axes([left, bottom+histheight, width, boxheight])
    histAx = fig.add_axes([left, bottom, width, histheight])

    # plot stuff
    bpAx.bxp(data_stats, vert=False, flierprops={"marker": 'x'})
    histAx.hist(data, bins=bins, color=colour)

    # confirm that the axes line up
    xlims = np.array([bpAx.get_xlim(), histAx.get_xlim()])
    for ax in [bpAx, histAx]:
        ax.set_xlim([xlims.min(), xlims.max()])

    bpAx.set_xticklabels([])  # clear out overlapping xlabels
    bpAx.set_yticks([])  # don't need that 1 tick mark
    bpAx.set_title(title,fontsize=20)

    histAx.set_xticks(xticks)
    histAx.get_xaxis().tick_bottom()
    bpAx.get_xaxis().tick_top()

with open("../../data/men") as f:
    men = [float(x) for x in f.readlines()]

with open("../../data/women") as f:
    women = [float(x) for x in f.readlines()]

fig = plt.figure(figsize=(12,8))
xticks = np.arange(5,105,5)
bins = 0.5 + np.arange(0,100)

boxhistplot(men, fig=fig, rect=[0.05, 0.55, 0.9, 0.35], xticks=xticks,
            colour=[0.3, 0.3, 1],
            bins=bins, title="Ages of actors")

boxhistplot(women, fig=fig, rect=[0.05, 0.1, 0.9, 0.35], xticks=xticks,
            colour='pink',
            bins=bins, title="Ages of actresses")

plt.savefig("boys-and-girls.pdf")