3
df = { 'id' : pd.Series([1,1,1,1,2,2,2,2,3,3,4,4,4])}

num_id = df['id'].value_counts().hist(bins=2)

I an get a nice histogram with the count of number of ids that fall into each bin.

Question is, how do i add annotations to each bar to show the count? It could be in the middle with white text.

I know there is an ax parameter that we can specify in hist() but i am not sure how.

enter image description here

2
  • ax.text is what you need. You can tie the x and y coordinates to the bin edges hist returns... Commented Oct 16, 2016 at 6:17
  • Could you show how? Commented Oct 16, 2016 at 6:20

1 Answer 1

4

Here you are (with the import statements, just in case):

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({ 'id' : [1,1,1,1,2,2,2,2,3,3,4,4,4]})

fig, ax = plt.subplots()
freq, bins, _ = ax.hist(df['id'].value_counts(), 2, facecolor='skyblue')
ax.grid(True)
for i, n in enumerate(freq):
    ax.text(bins[i]+0.5, 2, n)
ax.set_xlabel('Bins')
ax.set_ylabel('Freq')
plt.show()

Histogram, with Text

Sign up to request clarification or add additional context in comments.

Comments

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.