maniciam
maniciam

Reputation: 375

Displaying bins correctly with pyplot

Probably a simple question with a simple fix, but I'm sorta confused as to how binning actually works. I want to plot a fairly simple histogram. The x-axis should only have two values, 0 and 1, and the y-axis has floats between 0 and 1.0 representing the frequency of each of those values. Both 0 and 1 are the only values within the array, and yet when I show my histogram, the bins do not seem to line up with 0 and 1, and there are several tick marks on the x axis that are unneccessary. How can I make this graph such that only two ticks show up on x axis (0 and 1), and the respective frequency columns for each of those values displays correctly above the tick?

Here is my code:

trials = []
for i in range (m):
    trials.append(bernoulli_trial(p))
plt.figure(1)
plt.hist(trials, bins=2, align="mid", weights=np.zeros_like(trials) + 1. / len(trials))
plt.ylim(0,1.0)
plt.title("Bernoulli Distribution with p = " + str(p))
plt.xlabel("Outcome")
plt.ylabel("Probability")    
plt.show()

Can anyone offer any insight on what I'm doing wrong here?

Upvotes: 0

Views: 982

Answers (1)

daedalus
daedalus

Reputation: 10923

plt.figure(1)
plt.hist(trials, bins=2, align="mid",
         weights=np.zeros_like(trials) + 1. / len(trials))


# ------------------------------
# New lines to add tick marks as requested
tick_locs = [0.25, 0.75]
tick_lbls = ['0','1']
plt.xticks(tick_locs, tick_lbls)
# ------------------------------

plt.ylim(0,1.0)
plt.title("Bernoulli Distribution with p = " + str(p))
plt.xlabel("Outcome")
plt.ylabel("Probability")    
plt.show()

Upvotes: 1

Related Questions