How it works…

We start this example by simulating populations of males and females, according to the known parameters for the distribution of heights in each subpopulation. Since heights are normally distributed, we use the norm object from the scipy.stats module to generate the data. For example, the male population is generated with the following statement:

mdata = mdist.rvs(size=nm)

After the data is generated, we issue the plt.figure(figsize=(12, 4)) function call, which sets the figure dimensions. The histogram is then generated by executing the following code:

plt.subplot(1,2,1)
plt.hist([mdata, fdata], bins=20,
label=['Males', 'Females'])
plt.legend()
plt.xlabel('Height (inches)')
plt.ylabel('Frequency')

Since we want the plots to appear side by side, we use the plt.subplot(1,2,1) command, which specifies a layout with one row and two columns, and sets the current target graph to be in the first one. The hist() function is then called with the following arguments:

  • [mdata, fdata] is a list containing the datasets to be displayed in the histogram. By default, multiple datasets are displayed side by side.
  • bins=20 sets the number of bins to be used in the histogram.
  • label=['Males', 'Females'] specifies the labels to be used for each dataset in the legend.

Next, calling plt.legend() causes the legend to be added to the graph and we also set the labels in the two axes with calls to xlabel() and ylabel().

The next statements plot the box plot with the following lines of code:

plt.subplot(1,2,2)
plt.boxplot([mdata, fdata], patch_artist=True,
labels=['Males', 'Females'])

After selecting the subplot, we call the boxplot() function to generate the plot, with the two datasets given in the first argument. The patch_artist=True option directs Matplotlib to use the Artist interface, which produces a nicer plot. Finally, labels=['Males', 'Females'] sets the labels along the x axis for each of the box plots.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset