0

I want to plot a very simple histogram diagram with python. Here is my code :

from numpy import *
from matplotlib.pyplot import*
from random import*
nums = []
N = 10
for i in range(N):
    a = randint(0,10)
    nums.append(a)

bars= [0,1,2,3,4,5,6,7,8,9]
hist(nums)

show()

This is the result

How can I put the bars just in the integer place? Why does my diagram show the float numbers too?

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
aaa
  • 161
  • 1
  • 1
  • 8
  • 1
    Maybe the answers in this question already help you: http://stackoverflow.com/questions/12050393/force-the-y-axis-to-only-use-integers – R. Voigt Oct 23 '15 at 22:53
  • hist by default uses 10 bins but in the min to max range which is not 0 to 10 since your numbers are random – Azad Oct 23 '15 at 23:02

1 Answers1

2

you make bars but then don't use it. If you set the bins option of hist to bars, it all works fine

bars= [0,1,2,3,4,5,6,7,8,9]
hist(nums,bins=bars)

enter image description here

To set the yticks to only integer values, you can use a MultipleLocator from the matplotlib.ticker module:

from numpy import *
from matplotlib.pyplot import*
import matplotlib.ticker as ticker
from random import*

nums = []
N = 10
for i in range(N):
    a = randint(0,10)
    nums.append(a)

bars= [0,1,2,3,4,5,6,7,8,9]
hist(nums,bins=bars)

gca().yaxis.set_major_locator(ticker.MultipleLocator(1))

show()

enter image description here

tmdavison
  • 64,360
  • 12
  • 187
  • 165
  • i think he wants to remove 0.5, 1.5 etc from the Y axis. – MK. Oct 23 '15 at 23:56
  • thanks,How can add density plot to this? something like this : http://www.stata.com/support/faqs/graphics/histograms-with-varying-bin-widths/ the red curve I mean – aaa Oct 24 '15 at 07:02