Get startedGet started for free

Plotting the Binomial PMF

As mentioned in the video, plotting a nice looking PMF requires a bit of matplotlib trickery that we will not go into here. Instead, we will plot the PMF of the Binomial distribution as a histogram with skills you have already learned. The trick is setting up the edges of the bins to pass to plt.hist() via the bins keyword argument. We want the bins centered on the integers. So, the edges of the bins should be -0.5, 0.5, 1.5, 2.5, ... up to max(n_defaults) + 1.5. You can generate an array like this using np.arange() and then subtracting 0.5 from the array.

You have already sampled out of the Binomial distribution during your exercises on loan defaults, and the resulting samples are in the NumPy array n_defaults.

This exercise is part of the course

Statistical Thinking in Python (Part 1)

View Course

Exercise instructions

  • Using np.arange(), compute the bin edges such that the bins are centered on the integers. Store the resulting array in the variable bins.
  • Use plt.hist() to plot the histogram of n_defaults with the density=True and bins=bins keyword arguments.
  • Show the plot.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Compute bin edges: bins
bins = np.arange(____, ____ + ____) - 0.5

# Generate histogram


# Label axes



# Show the plot
Edit and Run Code