user3448011
user3448011

Reputation: 1599

matplotlib mark out only the highest bar with its frequency value in histogram

I would like to mark out the highest bar with its frequency value in a histogram created by matplotlib in python 3.7.

The data is dataframe of pandas.

Just like in this figure, How to automatically annotate maximum value in pyplot?

but, my plot is histogram. I do not want to mark each bar with its value.

Upvotes: 0

Views: 2375

Answers (1)

Nathaniel
Nathaniel

Reputation: 3290

Here is a method to plot a histogram with the frequency value shown on the highest bar:

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(0)

# Generate data
data = np.random.normal(0,1,200)

# Plot histogram
plt.figure()
y, x, _ = plt.hist(data, histtype='bar', edgecolor='darkgray', bins=15)

# Compute the max value (plt.hist returns the x and y positions of the bars)
ymax = y.max()
idx = np.where(y == ymax)[0][0]
xval = x[idx]

# Annotate the highest value
plt.gca().text(xval, ymax, ymax, ha='left', va='bottom')

Histogram with highest value annotated

Upvotes: 3

Related Questions