Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You're using different bins in the two cases. In your case, <code>np.linspace(xmin, xmax, (xmax-xmin)/step)</code> has 5 bins, but you've told <code>plt.hist</code> to use 6 bins.</p> <p>You can see this by looking at the output of each:</p> <pre><code>h1 = np.histogram(s, bins=np.linspace(xmin, xmax, (xmax-xmin)/step)) h_plt = plt.hist(s, bins=6,alpha=0.5) </code></pre> <p>Then:</p> <pre><code>&gt;&gt;&gt; h1[1] array([ 1. , 2.2, 3.4, 4.6, 5.8, 7. ]) &gt;&gt;&gt; h_plt[1] array([ 1., 2., 3., 4., 5., 6., 7.]) </code></pre> <p>I would use:</p> <pre><code>y, x = np.histogram(s, bins=np.linspace(xmin, xmax, (xmax-xmin)/step)) nbins = y.size # ... plt.hist(s, bins=nbins, alpha=0.5) </code></pre> <p>Then your histograms match, but your plot still won't because you've plotted the output of your <code>np.histogram</code> at the centers of the bins, but <code>plt.bar</code> expects an array of the left edges:</p> <blockquote> <p><code>plt.bar(left, height, width=0.8, bottom=None, hold=None, **kwargs)</code> </p> <p>Parameters<br> <code>----------</code><br> <code>left</code> : sequence of scalars<br> the <code>x</code> coordinates of the left sides of the bars</p> <p><code>height</code> : sequence of scalars<br> the heights of the bars</p> </blockquote> <p>What you want is:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt s = [1,1,1,1,2,2,2,3,3,4,5,5,5,6,7,7,7,7,7,7,7] xmin = 1 xmax = 7 step = 1 y, x = np.histogram(s, bins=np.linspace(xmin, xmax, (xmax-xmin)/step)) nbins = y.size plt.bar(x[:-1], y, width=x[1]-x[0], color='red', alpha=0.5) plt.hist(s, bins=nbins, alpha=0.5) plt.grid(True) plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/fIMtW.png" alt="two hists"></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload