joe963
joe963

Reputation: 13

How to plot histogram, when the number of values in interval is given? (python)

I know that when you usually plot a histogram you have an array of values and intervals. But if I have intervals and the number of values that are in those intervals, how can I plot the histogram?

I have something that looks like this:

amounts = np.array([23, 7, 18, 5])

and my interval is from 0 to 4 with step 1, so on interval [0,1] there are 23 values and so on.

Upvotes: 0

Views: 591

Answers (3)

Andrew
Andrew

Reputation: 799

If you already know the values, then the histogram just becomes a bar plot.

amounts = np.array([23, 7, 18, 5])
interval = np.arange(5)
midvals = (interval + 0.5)[0:len(vals)-1] # 0.5, 1.5, 2.5, 3.5

plt.bar(midvals, 
    amounts)
plt.xticks(interval) # Shows the interval ranges rather than the centers of the bars

plt.show()

bar plot/histogram

If the gap between the bars looks to wide, you can change the width of the bars by passing in a width (as a fraction of 1 - default is 0.8) argument to plt.bar().

Upvotes: 0

esskayesss
esskayesss

Reputation: 108

You could probably try matplotlib.pyplot.stairs for this.

import matplotlib.pyplot as plt
import numpy as np

amounts = np.array([23, 7, 18, 5])
plt.stairs(amounts, range(5))

plt.show()

Please mark it as solved if this helps.

Upvotes: 1

Yang Yushi
Yang Yushi

Reputation: 765

I find it easier to just simulate some data having the desired distribution, and then use plt.hist to plot the histogram.

Here is am example. Hopefully it will be helpful!

import numpy as np
import matplotlib.pyplot as plt


amounts = np.array([23, 7, 18, 5])
bin_edges = np.arange(5)
bin_centres = (bin_edges[1:] + bin_edges[:-1]) / 2

# fake some data having the desired distribution
data = [[bc] * amount for bc, amount in zip(bin_centres, amounts)]
data = np.concatenate(data)

hist = plt.hist(data, bins=bin_edges, histtype='step')[0]
plt.show()

# the plotted distribution is consistent with amounts
assert np.allclose(hist, amounts)

Upvotes: 0

Related Questions