0

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?

1

1 Answer 1

1
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()
Sign up to request clarification or add additional context in comments.

1 Comment

Lol wow perfect fix. I had tried to use xticks before, but I think I may have formatted it incorrectly so it really messed with the layout. Thanks alot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.